xref: /trunk/main/sc/source/ui/vba/vbaapplication.cxx (revision 7a7771fb4d20b857459c676939e2cc2f4dec9635)
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 #include <stdio.h>
25 
26 #include <com/sun/star/sheet/XSpreadsheetView.hpp>
27 #include <com/sun/star/sheet/XSpreadsheets.hpp>
28 #include <com/sun/star/view/XSelectionSupplier.hpp>
29 #include <com/sun/star/lang/XServiceInfo.hpp>
30 #include <ooo/vba/excel/XlCalculation.hpp>
31 #include <com/sun/star/sheet/XCellRangeReferrer.hpp>
32 #include <com/sun/star/sheet/XCalculatable.hpp>
33 #include <com/sun/star/frame/XLayoutManager.hpp>
34 #include <com/sun/star/frame/XModel.hpp>
35 #include <com/sun/star/script/provider/XScript.hpp>
36 #include <com/sun/star/script/provider/XScriptProvider.hpp>
37 #include <com/sun/star/script/provider/XScriptProviderSupplier.hpp>
38 #include <com/sun/star/task/XStatusIndicatorSupplier.hpp>
39 #include <com/sun/star/task/XStatusIndicator.hpp>
40 #include <ooo/vba/excel/XlMousePointer.hpp>
41 #include <com/sun/star/sheet/XNamedRanges.hpp>
42 #include <com/sun/star/sheet/XCellRangeAddressable.hpp>
43 #include <ooo/vba/XExecutableDialog.hpp>
44 
45 #include "vbaapplication.hxx"
46 #include "vbaworkbooks.hxx"
47 #include "vbaworkbook.hxx"
48 #include "vbaworksheets.hxx"
49 #include "vbarange.hxx"
50 #include "vbawsfunction.hxx"
51 #include "vbadialogs.hxx"
52 #include "vbawindow.hxx"
53 #include "vbawindows.hxx"
54 #include "vbaglobals.hxx"
55 #include "tabvwsh.hxx"
56 #include "gridwin.hxx"
57 #include "vbanames.hxx"
58 #include <vbahelper/vbashape.hxx>
59 #include "vbatextboxshape.hxx"
60 #include "vbaassistant.hxx"
61 #include "vbafiledialog.hxx"
62 #include "vbafilesearch.hxx"
63 #include "sc.hrc"
64 #include "global.hxx"
65 #include "scmod.hxx"
66 #include "docoptio.hxx"
67 #include "appoptio.hxx"
68 
69 #include <osl/file.hxx>
70 #include <rtl/instance.hxx>
71 
72 #include <sfx2/request.hxx>
73 #include <sfx2/objsh.hxx>
74 #include <sfx2/viewfrm.hxx>
75 #include <sfx2/app.hxx>
76 
77 #include <toolkit/awt/vclxwindow.hxx>
78 #include <toolkit/helper/vclunohelper.hxx>
79 
80 #include <vcl/svapp.hxx>
81 #include <unotools/syslocale.hxx>
82 #include <unotools/localedatawrapper.hxx>
83 #include <unotools/calendarwrapper.hxx>
84 #include <tools/datetime.hxx>
85 
86 #include <tools/diagnose_ex.h>
87 
88 #include <docuno.hxx>
89 
90 #include <basic/sbx.hxx>
91 #include <basic/sbstar.hxx>
92 #include <basic/sbuno.hxx>
93 #include <basic/sbmeth.hxx>
94 
95 #include "convuno.hxx"
96 #include "cellsuno.hxx"
97 #include "docsh.hxx"
98 #include <vbahelper/helperdecl.hxx>
99 #include "excelvbahelper.hxx"
100 
101 #include <svl/undo.hxx>
102 
103 
104 using namespace ::ooo::vba;
105 using namespace ::com::sun::star;
106 
107 // #TODO is this defined somewhere else?
108 #if ( defined UNX ) || ( defined OS2 ) //unix
109 #define FILE_PATH_SEPERATOR "/"
110 #else // windows
111 #define FILE_PATH_SEPERATOR "\\"
112 #endif
113 
114 uno::Any sbxToUnoValue( SbxVariable* pVar );
115 
116 // ============================================================================
117 
118 /** Global application settings shared by all open workbooks. */
119 struct ScVbaAppSettings
120 {
121     sal_Int32 mnCalculation;
122     sal_Bool mbDisplayAlerts;
123     sal_Bool mbEnableEvents;
124 
125     explicit ScVbaAppSettings();
126 };
127 
ScVbaAppSettings()128 ScVbaAppSettings::ScVbaAppSettings() :
129     mnCalculation( excel::XlCalculation::xlCalculationAutomatic ),
130     mbDisplayAlerts( sal_True ),
131     mbEnableEvents( sal_True )
132 {
133 }
134 
135 struct ScVbaStaticAppSettings : public ::rtl::Static< ScVbaAppSettings, ScVbaStaticAppSettings > {};
136 
137 // ============================================================================
138 
139 // MS Excel VBA: Constructs the Application object with the component context.
140 // Status: implemented - initializes shared settings reference
ScVbaApplication(const uno::Reference<uno::XComponentContext> & xContext)141 ScVbaApplication::ScVbaApplication( const uno::Reference<uno::XComponentContext >& xContext ) :
142     ScVbaApplication_BASE( xContext ),
143     mrAppSettings( ScVbaStaticAppSettings::get() )
144 {
145 }
146 
147 // MS Excel VBA: Destructor for the Application object.
148 // Status: implemented
~ScVbaApplication()149 ScVbaApplication::~ScVbaApplication()
150 {
151 }
152 
153 // MS Excel VBA: Returns whether VBA document events are enabled.
154 // Status: implemented - reads from shared settings
getDocumentEventsEnabled()155 /*static*/ bool ScVbaApplication::getDocumentEventsEnabled()
156 {
157     return ScVbaStaticAppSettings::get().mbEnableEvents;
158 }
159 
160 // MS Excel VBA: Returns the document shell for the given model.
161 // Status: implemented - delegates to excel::getDocShell
GetDocShell(const uno::Reference<frame::XModel> & xModel)162 SfxObjectShell* ScVbaApplication::GetDocShell( const uno::Reference< frame::XModel >& xModel )
163 {
164     return static_cast< SfxObjectShell* >( excel::getDocShell( xModel ) );
165 }
166 
167 // MS Excel VBA: Returns the exact name of the specified object.
168 // Status: implemented - delegates to ScVbaWSFunction
169 ::rtl::OUString SAL_CALL
getExactName(const::rtl::OUString & aApproximateName)170 ScVbaApplication::getExactName( const ::rtl::OUString& aApproximateName )
171 {
172     uno::Reference< beans::XExactName > xWSF( new ScVbaWSFunction( this, mxContext ) );
173     return xWSF->getExactName( aApproximateName );
174 }
175 
176 // MS Excel VBA: Returns an XIntrospectionAccess for object introspection.
177 // Status: implemented - delegates to ScVbaWSFunction
178 uno::Reference< beans::XIntrospectionAccess > SAL_CALL
getIntrospection()179 ScVbaApplication::getIntrospection()
180 {
181     uno::Reference< script::XInvocation > xWSF( new ScVbaWSFunction( this, mxContext ) );
182     return xWSF->getIntrospection();
183 }
184 
185 // MS Excel VBA: Invokes a method by name on the Application.
186 // Status: implemented - delegates to ScVbaWSFunction, catches exceptions
187 uno::Any SAL_CALL
invoke(const::rtl::OUString & FunctionName,const uno::Sequence<uno::Any> & Params,uno::Sequence<sal_Int16> & OutParamIndex,uno::Sequence<uno::Any> & OutParam)188 ScVbaApplication::invoke( const ::rtl::OUString& FunctionName, const uno::Sequence< uno::Any >& Params, uno::Sequence< sal_Int16 >& OutParamIndex, uno::Sequence< uno::Any >& OutParam)
189 {
190     /*  When calling the functions directly at the Application object, no runtime
191         errors are thrown, but the error is inserted into the return value. */
192     uno::Any aAny;
193     try
194     {
195         uno::Reference< script::XInvocation > xWSF( new ScVbaWSFunction( this, mxContext ) );
196         aAny = xWSF->invoke( FunctionName, Params, OutParamIndex, OutParam );
197     }
198     catch( uno::Exception& )
199     {
200         aAny <<= script::BasicErrorException( ::rtl::OUString(), uno::Reference< uno::XInterface >(), 1000, ::rtl::OUString() );
201     }
202     return aAny;
203 }
204 
205 // MS Excel VBA: Sets a property by name on the Application.
206 // Status: implemented - delegates to ScVbaWSFunction
207 void SAL_CALL
setValue(const::rtl::OUString & PropertyName,const uno::Any & Value)208 ScVbaApplication::setValue( const ::rtl::OUString& PropertyName, const uno::Any& Value )
209 {
210     uno::Reference< script::XInvocation > xWSF( new ScVbaWSFunction( this, mxContext ) );
211     xWSF->setValue( PropertyName, Value );
212 }
213 
214 // MS Excel VBA: Gets a property by name on the Application.
215 // Status: implemented - delegates to ScVbaWSFunction
216 uno::Any SAL_CALL
getValue(const::rtl::OUString & PropertyName)217 ScVbaApplication::getValue( const ::rtl::OUString& PropertyName )
218 {
219     uno::Reference< script::XInvocation > xWSF( new ScVbaWSFunction( this, mxContext ) );
220     return xWSF->getValue( PropertyName );
221 }
222 
223 // MS Excel VBA: Returns true if the specified method exists on the Application.
224 // Status: implemented - checks for "Run" first, then delegates to ScVbaWSFunction
225 sal_Bool SAL_CALL
hasMethod(const::rtl::OUString & Name)226 ScVbaApplication::hasMethod( const ::rtl::OUString& Name )
227 {
228     // Application.Run is implemented as a typed method on XApplication
229     if( Name.equalsIgnoreAsciiCaseAscii( "Run" ) )
230         return sal_True;
231     uno::Reference< script::XInvocation > xWSF( new ScVbaWSFunction( this, mxContext ) );
232     return xWSF->hasMethod( Name );
233 }
234 
235 // MS Excel VBA: Returns true if the specified property exists on the Application.
236 // Status: implemented - delegates to ScVbaWSFunction
237 sal_Bool SAL_CALL
hasProperty(const::rtl::OUString & Name)238 ScVbaApplication::hasProperty( const ::rtl::OUString& Name )
239 {
240     uno::Reference< script::XInvocation > xWSF( new ScVbaWSFunction( this, mxContext ) );
241     return xWSF->hasProperty( Name );
242 }
243 
244 // MS Excel VBA: Returns the active workbook (the workbook receiving input focus).
245 // Status: implemented - creates ScVbaWorkbook if not already a VBA document
246 uno::Reference< excel::XWorkbook >
getActiveWorkbook()247 ScVbaApplication::getActiveWorkbook()
248 {
249     uno::Reference< frame::XModel > xModel( getCurrentExcelDoc( mxContext ), uno::UNO_SET_THROW );
250     uno::Reference< excel::XWorkbook > xWorkbook( getVBADocument( xModel ), uno::UNO_QUERY );
251     if( xWorkbook.is() ) return xWorkbook;
252     // #i116936# getVBADocument() may return null in documents without global VBA mode enabled
253     return new ScVbaWorkbook( this, mxContext, xModel );
254 }
255 
256 // MS Excel VBA: Returns the workbook where the VBA code is running (ThisWorkbook).
257 // Status: implemented - creates ScVbaWorkbook if not already a VBA document
258 uno::Reference< excel::XWorkbook > SAL_CALL
getThisWorkbook()259 ScVbaApplication::getThisWorkbook()
260 {
261     uno::Reference< frame::XModel > xModel( getThisExcelDoc( mxContext ), uno::UNO_SET_THROW );
262     uno::Reference< excel::XWorkbook > xWorkbook( getVBADocument( xModel ), uno::UNO_QUERY );
263     if( xWorkbook.is() ) return xWorkbook;
264     // #i116936# getVBADocument() may return null in documents without global VBA mode enabled
265     return new ScVbaWorkbook( this, mxContext, xModel );
266 }
267 
268 // MS Excel VBA: Returns the Assistant (Office Assistant) object.
269 // Status: implemented - creates ScVbaAssistant
270 uno::Reference< XAssistant > SAL_CALL
getAssistant()271 ScVbaApplication::getAssistant()
272 {
273     return uno::Reference< XAssistant >( new ScVbaAssistant( this, mxContext ) );
274 }
275 
276 // MS Excel VBA: Returns the current selection (Range, Shape, or Collection).
277 // Status: implemented - supports shapes and cell range selections
278 uno::Any SAL_CALL
getSelection()279 ScVbaApplication::getSelection()
280 {
281     OSL_TRACE("** ScVbaApplication::getSelection() ** ");
282     uno::Reference< frame::XModel > xModel( getCurrentDocument() );
283     uno::Reference< lang::XServiceInfo > xServiceInfo( xModel->getCurrentSelection(), uno::UNO_QUERY_THROW );
284     rtl::OUString sImpementaionName = xServiceInfo->getImplementationName();
285     if( sImpementaionName.equalsIgnoreAsciiCaseAscii("com.sun.star.drawing.SvxShapeCollection") )
286     {
287         uno::Reference< drawing::XShapes > xShapes( xModel->getCurrentSelection(), uno::UNO_QUERY_THROW );
288         uno::Reference< container::XIndexAccess > xIndexAccess( xShapes, uno::UNO_QUERY_THROW );
289         uno::Reference< drawing::XShape > xShape( xIndexAccess->getByIndex(0), uno::UNO_QUERY_THROW );
290     // if ScVbaShape::getType( xShape ) == office::MsoShapeType::msoAutoShape
291     // and the uno object implements the com.sun.star.drawing.Text service
292     // return a textboxshape object
293     if ( ScVbaShape::getType( xShape ) == office::MsoShapeType::msoAutoShape )
294     {
295         uno::Reference< lang::XServiceInfo > xShapeServiceInfo( xShape, uno::UNO_QUERY_THROW );
296         if ( xShapeServiceInfo->supportsService( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.drawing.Text" ) ) )  )
297         {
298                 return uno::makeAny( uno::Reference< msforms::XTextBoxShape >(new ScVbaTextBoxShape( mxContext, xShape, xShapes, xModel ) ) );
299         }
300     }
301         return uno::makeAny( uno::Reference< msforms::XShape >(new ScVbaShape( this, mxContext, xShape, xShapes, xModel, ScVbaShape::getType( xShape ) ) ) );
302     }
303     else if( xServiceInfo->supportsService( rtl::OUString::createFromAscii("com.sun.star.sheet.SheetCellRange")) ||
304              xServiceInfo->supportsService( rtl::OUString::createFromAscii("com.sun.star.sheet.SheetCellRanges")))
305     {
306         uno::Reference< table::XCellRange > xRange( getCurrentDocument()->getCurrentSelection(), ::uno::UNO_QUERY);
307         if ( !xRange.is() )
308         {
309             uno::Reference< sheet::XSheetCellRangeContainer > xRanges( getCurrentDocument()->getCurrentSelection(), ::uno::UNO_QUERY);
310             if ( xRanges.is() )
311                 return uno::makeAny( uno::Reference< excel::XRange >( new ScVbaRange( excel::getUnoSheetModuleObj( xRanges ), mxContext, xRanges ) ) );
312 
313         }
314         return uno::makeAny( uno::Reference< excel::XRange >(new ScVbaRange( excel::getUnoSheetModuleObj( xRange ), mxContext, xRange ) ) );
315     }
316     else
317     {
318         throw uno::RuntimeException( sImpementaionName + rtl::OUString::createFromAscii(" not supported"), uno::Reference< uno::XInterface >() );
319     }
320 }
321 
322 // MS Excel VBA: Returns the active cell in the active sheet.
323 // Status: implemented - uses view cursor position
324 uno::Reference< excel::XRange >
getActiveCell()325 ScVbaApplication::getActiveCell()
326 {
327     uno::Reference< sheet::XSpreadsheetView > xView( getCurrentDocument()->getCurrentController(), uno::UNO_QUERY_THROW );
328     uno::Reference< table::XCellRange > xRange( xView->getActiveSheet(), ::uno::UNO_QUERY_THROW);
329     ScTabViewShell* pViewShell = excel::getCurrentBestViewShell(mxContext);
330     if ( !pViewShell )
331         throw uno::RuntimeException( rtl::OUString::createFromAscii("No ViewShell available"), uno::Reference< uno::XInterface >() );
332     ScViewData* pTabView = pViewShell->GetViewData();
333     if ( !pTabView )
334         throw uno::RuntimeException( rtl::OUString::createFromAscii("No ViewData available"), uno::Reference< uno::XInterface >() );
335 
336     sal_Int32 nCursorX = pTabView->GetCurX();
337     sal_Int32 nCursorY = pTabView->GetCurY();
338 
339     // #i117392# excel::getUnoSheetModuleObj() may return null in documents without global VBA mode enabled
340     return new ScVbaRange( excel::getUnoSheetModuleObj( xRange ), mxContext, xRange->getCellRangeByPosition( nCursorX, nCursorY, nCursorX, nCursorY ) );
341 }
342 
343 // MS Excel VBA: Returns the Workbooks collection or a single workbook by index.
344 // Status: implemented - delegates to ScVbaWorkbooks collection
345 uno::Any SAL_CALL
Workbooks(const uno::Any & aIndex)346 ScVbaApplication::Workbooks( const uno::Any& aIndex )
347 {
348     uno::Reference< XCollection > xWorkBooks( new ScVbaWorkbooks( this, mxContext ) );
349     if (  aIndex.getValueTypeClass() == uno::TypeClass_VOID )
350     {
351         // void then somebody did Workbooks.something in vba
352         return uno::Any( xWorkBooks );
353     }
354 
355     return uno::Any ( xWorkBooks->Item( aIndex, uno::Any() ) );
356 }
357 
358 // MS Excel VBA: Returns the Worksheets collection or a single worksheet by index.
359 // Status: implemented - delegates to active workbook's Worksheets
360 uno::Any SAL_CALL
Worksheets(const uno::Any & aIndex)361 ScVbaApplication::Worksheets( const uno::Any& aIndex )
362 {
363     uno::Reference< excel::XWorkbook > xWorkbook( getActiveWorkbook(), uno::UNO_SET_THROW );
364     return xWorkbook->Worksheets( aIndex );
365 }
366 
367 // MS Excel VBA: Returns the WorksheetFunction object for built-in Excel functions.
368 // Status: implemented - creates ScVbaWSFunction
369 uno::Any SAL_CALL
WorksheetFunction()370 ScVbaApplication::WorksheetFunction( )
371 {
372     return uno::makeAny( uno::Reference< script::XInvocation >( new ScVbaWSFunction( this, mxContext ) ) );
373 }
374 
375 // MS Excel VBA: Evaluates an expression or range reference and returns the result.
376 // Status: partial - only supports range names, not arbitrary expressions
377 uno::Any SAL_CALL
Evaluate(const::rtl::OUString & Name)378 ScVbaApplication::Evaluate( const ::rtl::OUString& Name )
379 {
380     // #TODO Evaluate allows other things to be evaluated, e.g. functions
381     // I think ( like SIN(3) etc. ) need to investigate that
382     // named Ranges also? e.g. [MyRange] if so need a list of named ranges
383     uno::Any aVoid;
384     return uno::Any( getActiveWorkbook()->getActiveSheet()->Range( uno::Any( Name ), aVoid ) );
385 }
386 
387 // MS Excel VBA: Returns the Dialogs collection or a single dialog by index.
388 // Status: implemented - delegates to ScVbaDialogs
389 uno::Any
Dialogs(const uno::Any & aIndex)390 ScVbaApplication::Dialogs( const uno::Any &aIndex )
391 {
392     uno::Reference< excel::XDialogs > xDialogs( new ScVbaDialogs( uno::Reference< XHelperInterface >( this ), mxContext, getCurrentDocument() ) );
393     if( !aIndex.hasValue() )
394         return uno::Any( xDialogs );
395     return uno::Any( xDialogs->Item( aIndex ) );
396 }
397 
398 // MS Excel VBA: Returns the active window.
399 // Status: implemented - wraps XController in ScVbaWindow
400 uno::Reference< excel::XWindow > SAL_CALL
getActiveWindow()401 ScVbaApplication::getActiveWindow()
402 {
403     uno::Reference< frame::XModel > xModel = getCurrentDocument();
404     uno::Reference< frame::XController > xController( xModel->getCurrentController(), uno::UNO_SET_THROW );
405     uno::Reference< XHelperInterface > xParent( getActiveWorkbook(), uno::UNO_QUERY_THROW );
406     uno::Reference< excel::XWindow > xWin( new ScVbaWindow( xParent, mxContext, xModel, xController ) );
407     return xWin;
408 }
409 
410 // MS Excel VBA: Returns the cut/copy mode status (True if cutting/copying).
411 // Status: stubbed - always returns False
412 uno::Any SAL_CALL
getCutCopyMode()413 ScVbaApplication::getCutCopyMode()
414 {
415     //# FIXME TODO, implementation
416     uno::Any result;
417     result <<= sal_False;
418     return result;
419 }
420 
421 // MS Excel VBA: Sets the cut/copy mode status.
422 // Status: stubbed - no-op (parameter ignored)
423 void SAL_CALL
setCutCopyMode(const uno::Any &)424 ScVbaApplication::setCutCopyMode( const uno::Any& /*_cutcopymode*/ )
425 {
426     //# FIXME TODO, implementation
427 }
428 
429 // MS Excel VBA: Returns or sets the text in the status bar.
430 // Status: implemented - get returns DisplayStatusBar flag, set uses XStatusIndicator
431 uno::Any SAL_CALL
getStatusBar()432 ScVbaApplication::getStatusBar()
433 {
434     return uno::makeAny( !getDisplayStatusBar() );
435 }
436 
437 // MS Excel VBA: Sets the text in the status bar or restores default display.
438 // Status: implemented - uses UNO XStatusIndicator
439 void SAL_CALL
setStatusBar(const uno::Any & _statusbar)440 ScVbaApplication::setStatusBar( const uno::Any& _statusbar )
441 {
442     rtl::OUString sText;
443     sal_Bool bDefault = sal_False;
444     uno::Reference< frame::XModel > xModel( getCurrentDocument(), uno::UNO_QUERY_THROW );
445     uno::Reference< task::XStatusIndicatorSupplier > xStatusIndicatorSupplier( xModel->getCurrentController(), uno::UNO_QUERY_THROW );
446     uno::Reference< task::XStatusIndicator > xStatusIndicator( xStatusIndicatorSupplier->getStatusIndicator(), uno::UNO_QUERY_THROW );
447     if( _statusbar >>= sText )
448     {
449         setDisplayStatusBar( sal_True );
450         if ( sText.getLength() )
451             xStatusIndicator->start( sText, 100 );
452         else
453             xStatusIndicator->end();        // restore normal state for empty text
454     }
455     else if( _statusbar >>= bDefault )
456     {
457         if( bDefault == sal_False )
458         {
459             xStatusIndicator->end();
460             setDisplayStatusBar( sal_True );
461         }
462     }
463     else
464         throw uno::RuntimeException( rtl::OUString::createFromAscii( "Invalid prarameter. It should be a string or False" ),
465             uno::Reference< uno::XInterface >() );
466 }
467 
468 // MS Excel VBA: Returns the calculation mode (automatic, manual, or semiautomatic).
469 // Status: implemented - reads from current document's XCalculatable
470 // TODO in Excel, this is an application-wide setting
471 ::sal_Int32 SAL_CALL
getCalculation()472 ScVbaApplication::getCalculation()
473 {
474     uno::Reference<sheet::XCalculatable> xCalc(getCurrentDocument(), uno::UNO_QUERY_THROW);
475     if(xCalc->isAutomaticCalculationEnabled())
476         return excel::XlCalculation::xlCalculationAutomatic;
477     else
478         return excel::XlCalculation::xlCalculationManual;
479 }
480 
481 // MS Excel VBA: Sets the calculation mode (automatic, manual, or semiautomatic).
482 // Status: implemented - delegates to current document's XCalculatable
483 void SAL_CALL
setCalculation(::sal_Int32 _calculation)484 ScVbaApplication::setCalculation( ::sal_Int32 _calculation )
485 {
486     // TODO: in Excel, this is an application-wide setting
487     uno::Reference< sheet::XCalculatable > xCalc(getCurrentDocument(), uno::UNO_QUERY_THROW);
488     switch(_calculation)
489     {
490         case excel::XlCalculation::xlCalculationManual:
491             xCalc->enableAutomaticCalculation(sal_False);
492             break;
493         case excel::XlCalculation::xlCalculationAutomatic:
494         case excel::XlCalculation::xlCalculationSemiautomatic:
495             xCalc->enableAutomaticCalculation(sal_True);
496             break;
497     }
498 }
499 
500 // MS Excel VBA: Returns the Windows collection or a single window by index.
501 // Status: implemented - delegates to ScVbaWindows
502 uno::Any SAL_CALL
Windows(const uno::Any & aIndex)503 ScVbaApplication::Windows( const uno::Any& aIndex  )
504 {
505     uno::Reference< excel::XWindows >  xWindows( new ScVbaWindows( this, mxContext ) );
506     if ( aIndex.getValueTypeClass() == uno::TypeClass_VOID )
507         return uno::Any( xWindows );
508     return uno::Any( xWindows->Item( aIndex, uno::Any() ) );
509 }
510 // MS Excel VBA: Pauses execution for the specified time (in seconds).
511 // Status: implemented - uses WaitUntil BASIC function
512 void SAL_CALL
wait(double time)513 ScVbaApplication::wait( double time )
514 {
515     StarBASIC* pBasic = SFX_APP()->GetBasic();
516     SbxArrayRef aArgs = new SbxArray;
517     SbxVariableRef aRef = new SbxVariable;
518     aRef->PutDouble( time );
519     aArgs->Put(  aRef, 1 );
520     SbMethod* pMeth = (SbMethod*)pBasic->GetRtl()->Find( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("WaitUntil") ), SbxCLASS_METHOD );
521 
522     if ( pMeth )
523     {
524         pMeth->SetParameters( aArgs );
525         SbxVariableRef refTemp = pMeth;
526         // forces a broadcast
527         SbxVariableRef pNew = new  SbxMethod( *((SbxMethod*)pMeth));
528     }
529 }
530 
531 // MS Excel VBA: Returns the Range object for the given cell references.
532 // Status: implemented - delegates to ScVbaRange::ApplicationRange
533 uno::Any SAL_CALL
Range(const uno::Any & Cell1,const uno::Any & Cell2)534 ScVbaApplication::Range( const uno::Any& Cell1, const uno::Any& Cell2 )
535 {
536     uno::Reference< excel::XRange > xVbRange = ScVbaRange::ApplicationRange( mxContext, Cell1, Cell2 );
537     return uno::makeAny( xVbRange );
538 }
539 
540 // MS Excel VBA: Returns the Names collection or a single defined name by index.
541 // Status: implemented - delegates to ScVbaNames
542 uno::Any SAL_CALL
Names(const css::uno::Any & aIndex)543 ScVbaApplication::Names( const css::uno::Any& aIndex )
544 {
545     uno::Reference< frame::XModel > xModel( getCurrentDocument(), uno::UNO_QUERY_THROW );
546     uno::Reference< beans::XPropertySet > xPropertySet( xModel, uno::UNO_QUERY_THROW );
547     uno::Reference< sheet::XNamedRanges > xNamedRanges( xPropertySet->getPropertyValue( rtl::OUString::createFromAscii("NamedRanges")) , uno::UNO_QUERY_THROW );
548     css::uno::Reference< excel::XNames > xNames ( new ScVbaNames( this , mxContext , xNamedRanges , xModel ) );
549     if (  aIndex.getValueTypeClass() == uno::TypeClass_VOID )
550     {
551         return uno::Any( xNames );
552 }
553     return uno::Any( xNames->Item( aIndex, uno::Any() ) );
554 }
555 
556 
557 // MS Excel VBA: Returns the active sheet in the active workbook.
558 // Status: implemented - throws RuntimeException if no active sheet
559 uno::Reference< excel::XWorksheet > SAL_CALL
getActiveSheet()560 ScVbaApplication::getActiveSheet()
561 {
562     uno::Reference< excel::XWorksheet > result;
563     uno::Reference< excel::XWorkbook > xWorkbook( getActiveWorkbook(), uno::UNO_QUERY );
564     if ( xWorkbook.is() )
565     {
566         uno::Reference< excel::XWorksheet > xWorksheet(
567             xWorkbook->getActiveSheet(), uno::UNO_QUERY );
568         if ( xWorksheet.is() )
569         {
570             result = xWorksheet;
571         }
572     }
573 
574     if ( !result.is() )
575     {
576         // Fixme - check if this is reasonable/desired behavior
577         throw uno::RuntimeException( rtl::OUString::createFromAscii(
578             "No activeSheet available" ), uno::Reference< uno::XInterface >() );
579     }
580     return result;
581 
582 }
583 
584 /*******************************************************************************
585  *  In msdn:
586  *  Reference   Optional Variant. The destination. Can be a Range
587  *  object, a string that contains a cell reference in R1C1-style notation,
588  *  or a string that contains a Visual Basic procedure name.
589  *  Scroll   Optional Variant. True to scrol, False to not scroll through
590  *  the window. The default is False.
591  *  Parser is split to three parts, Range, R1C1 string and procedure name.
592  *  by test excel, it seems Scroll no effect. ???
593  *******************************************************************************/
594 // MS Excel VBA: Navigates to the specified range or selects the active cell.
595 // Status: implemented - supports Range objects, R1C1 strings; procedure names not supported
596 void SAL_CALL
GoTo(const uno::Any & Reference,const uno::Any & Scroll)597 ScVbaApplication::GoTo( const uno::Any& Reference, const uno::Any& Scroll )
598 {
599     //test Scroll is a boolean
600     sal_Bool bScroll = sal_False;
601     //R1C1-style string or a string of procedure name.
602 
603     if( Scroll.hasValue() )
604     {
605         sal_Bool aScroll = sal_False;
606         if( Scroll >>= aScroll )
607         {
608             bScroll = aScroll;
609         }
610         else
611             throw uno::RuntimeException( rtl::OUString::createFromAscii( "second parameter should be boolean" ),
612                     uno::Reference< uno::XInterface >() );
613     }
614 
615     rtl::OUString sRangeName;
616     if( Reference >>= sRangeName )
617     {
618         uno::Reference< frame::XModel > xModel( getCurrentDocument(), uno::UNO_QUERY_THROW );
619         uno::Reference< sheet::XSpreadsheetView > xSpreadsheet(
620                 xModel->getCurrentController(), uno::UNO_QUERY_THROW );
621         uno::Reference< sheet::XSpreadsheet > xDoc = xSpreadsheet->getActiveSheet();
622 
623         ScTabViewShell* pShell = excel::getCurrentBestViewShell( mxContext );
624         ScGridWindow* gridWindow = (ScGridWindow*)pShell->GetWindow();
625         try
626         {
627             uno::Reference< excel::XRange > xVbaSheetRange = ScVbaRange::getRangeObjectForName(
628                 mxContext, sRangeName, excel::getDocShell( xModel ), formula::FormulaGrammar::CONV_XL_R1C1 );
629 
630             if( bScroll )
631             {
632                 xVbaSheetRange->Select();
633                 uno::Reference< excel::XWindow >  xWindow = getActiveWindow();
634                 ScSplitPos eWhich = pShell->GetViewData()->GetActivePart();
635                 sal_Int32 nValueX = pShell->GetViewData()->GetPosX(WhichH(eWhich));
636                 sal_Int32 nValueY = pShell->GetViewData()->GetPosY(WhichV(eWhich));
637                 xWindow->SmallScroll( uno::makeAny( (sal_Int16)(xVbaSheetRange->getRow() - 1) ),
638                          uno::makeAny( (sal_Int16)nValueY ),
639                          uno::makeAny( (sal_Int16)(xVbaSheetRange->getColumn() - 1)  ),
640                          uno::makeAny( (sal_Int16)nValueX ) );
641                 gridWindow->GrabFocus();
642             }
643             else
644             {
645                 xVbaSheetRange->Select();
646                 gridWindow->GrabFocus();
647             }
648         }
649         catch( uno::RuntimeException )
650         {
651             //maybe this should be a procedure name
652             //TODO for procedure name
653             //browse::XBrowseNodeFactory is a singleton. OUString::createFromAscii( "/singletons/com.sun.star.script.browse.theBrowseNodeFactory")
654             //and the createView( browse::BrowseNodeFactoryViewTypes::MACROSELECTOR ) to get a root browse::XBrowseNode.
655             //for query XInvocation interface.
656             //but how to directly get the XInvocation?
657             throw uno::RuntimeException( rtl::OUString::createFromAscii( "invalid reference for range name, it should be procedure name" ),
658                     uno::Reference< uno::XInterface >() );
659         }
660         return;
661     }
662     uno::Reference< excel::XRange > xRange;
663     if( Reference >>= xRange )
664     {
665         uno::Reference< excel::XRange > xVbaRange( Reference, uno::UNO_QUERY );
666         ScTabViewShell* pShell = excel::getCurrentBestViewShell( mxContext );
667         ScGridWindow* gridWindow = (ScGridWindow*)pShell->GetWindow();
668         if ( xVbaRange.is() )
669         {
670             //TODO bScroll should be using, In this time, it doesenot have effection
671             if( bScroll )
672             {
673                 xVbaRange->Select();
674                 uno::Reference< excel::XWindow >  xWindow = getActiveWindow();
675                 ScSplitPos eWhich = pShell->GetViewData()->GetActivePart();
676                 sal_Int32 nValueX = pShell->GetViewData()->GetPosX(WhichH(eWhich));
677                 sal_Int32 nValueY = pShell->GetViewData()->GetPosY(WhichV(eWhich));
678                 xWindow->SmallScroll( uno::makeAny( (sal_Int16)(xVbaRange->getRow() - 1) ),
679                          uno::makeAny( (sal_Int16)nValueY ),
680                          uno::makeAny( (sal_Int16)(xVbaRange->getColumn() - 1)  ),
681                          uno::makeAny( (sal_Int16)nValueX ) );
682                 gridWindow->GrabFocus();
683             }
684             else
685             {
686                 xVbaRange->Select();
687                 gridWindow->GrabFocus();
688             }
689         }
690         return;
691     }
692     throw uno::RuntimeException( rtl::OUString::createFromAscii( "invalid reference or name" ),
693             uno::Reference< uno::XInterface >() );
694 }
695 
696 // MS Excel VBA: Returns the current mouse cursor pointer style.
697 // Status: implemented - maps VCL pointer style to XlMousePointer constants
698 sal_Int32 SAL_CALL
getCursor()699 ScVbaApplication::getCursor()
700 {
701     sal_Int32 nPointerStyle =  getPointerStyle(getCurrentDocument());
702 
703     switch( nPointerStyle )
704     {
705         case POINTER_ARROW:
706             return excel::XlMousePointer::xlNorthwestArrow;
707         case POINTER_NULL:
708             return excel::XlMousePointer::xlDefault;
709         case POINTER_WAIT:
710             return excel::XlMousePointer::xlWait;
711         case POINTER_TEXT:
712             return excel::XlMousePointer::xlIBeam;
713         default:
714             return excel::XlMousePointer::xlDefault;
715     }
716 }
717 
718 // MS Excel VBA: Sets the mouse cursor pointer style.
719 // Status: implemented - maps XlMousePointer constants to VCL pointer styles
720 void SAL_CALL
setCursor(sal_Int32 _cursor)721 ScVbaApplication::setCursor( sal_Int32 _cursor )
722 {
723     try
724     {
725     uno::Reference< frame::XModel > xModel( getCurrentDocument(), uno::UNO_QUERY_THROW );
726         switch( _cursor )
727         {
728             case excel::XlMousePointer::xlNorthwestArrow:
729             {
730                 const Pointer& rPointer( POINTER_ARROW );
731                 setCursorHelper( xModel, rPointer, sal_False );
732                 break;
733             }
734             case excel::XlMousePointer::xlWait:
735             case excel::XlMousePointer::xlIBeam:
736             {
737                 const Pointer& rPointer( static_cast< PointerStyle >( _cursor ) );
738                 //It will set the edit window, toobar and statusbar's mouse pointer.
739                 setCursorHelper( xModel, rPointer, sal_True );
740                 break;
741             }
742             case excel::XlMousePointer::xlDefault:
743             {
744                 const Pointer& rPointer( POINTER_NULL );
745                 setCursorHelper( xModel, rPointer, sal_False );
746                 break;
747             }
748             default:
749                 throw uno::RuntimeException( rtl::OUString(
750                         RTL_CONSTASCII_USTRINGPARAM("Unknown value for Cursor pointer")), uno::Reference< uno::XInterface >() );
751                 // TODO: isn't this a flaw in the API? It should be allowed to throw an
752                 // IllegalArgumentException, or so
753         }
754     }
755     catch( const uno::Exception& )
756     {
757         DBG_UNHANDLED_EXCEPTION();
758     }
759 }
760 
761 // MS Excel VBA: Returns the application name.
762 // Status: implemented - returns hardcoded "Microsoft Excel"
763 // #TODO perhaps we should switch the return type depending of the filter type
764 // #TODO type, e.g. return Calc for Calc and Excel if its an imported doc
765 rtl::OUString SAL_CALL
getName()766 ScVbaApplication::getName()
767 {
768     static rtl::OUString appName( RTL_CONSTASCII_USTRINGPARAM("Microsoft Excel" ) );
769     return appName;
770 }
771 
772 // MS Excel VBA: Sets whether status alerts are displayed.
773 // Status: implemented - stored in shared settings (displayAlerts flag)
774 // #TODO get/setDisplayAlerts are just stub impl - the status of the switch
775 // #TODO is set here just. The function that throws an error message needs
776 // #TODO to evaluate this switch to know whether to disable error messages.
777 void SAL_CALL
setDisplayAlerts(sal_Bool displayAlerts)778 ScVbaApplication::setDisplayAlerts(sal_Bool displayAlerts)
779 {
780     mrAppSettings.mbDisplayAlerts = displayAlerts;
781 }
782 
783 // MS Excel VBA: Returns whether status alerts are displayed.
784 // Status: implemented - returns shared settings flag
785 sal_Bool SAL_CALL
getDisplayAlerts()786 ScVbaApplication::getDisplayAlerts()
787 {
788     return mrAppSettings.mbDisplayAlerts;
789 }
790 
791 // MS Excel VBA: Sets whether events are enabled.
792 // Status: implemented - stored in shared settings (EnableEvents flag)
793 void SAL_CALL
setEnableEvents(sal_Bool bEnable)794 ScVbaApplication::setEnableEvents(sal_Bool bEnable)
795 {
796     mrAppSettings.mbEnableEvents = bEnable;
797 }
798 
799 // MS Excel VBA: Returns whether events are enabled.
800 // Status: implemented - returns shared settings flag
801 sal_Bool SAL_CALL
getEnableEvents()802 ScVbaApplication::getEnableEvents()
803 {
804     return mrAppSettings.mbEnableEvents;
805 }
806 
807 // MS Excel VBA: Recalculates all open workbooks.
808 // Status: implemented - calls UNO XCalculatable::calculateAll
809 void SAL_CALL
Calculate()810 ScVbaApplication::Calculate()
811 {
812     uno::Reference< frame::XModel > xModel( getCurrentDocument(), uno::UNO_QUERY_THROW );
813     uno::Reference< sheet::XCalculatable > xCalculatable( getCurrentDocument(), uno::UNO_QUERY_THROW );
814     xCalculatable->calculateAll();
815 }
816 
lcl_getPathSettingsService(const uno::Reference<uno::XComponentContext> & xContext)817 uno::Reference< beans::XPropertySet > lcl_getPathSettingsService( const uno::Reference< uno::XComponentContext >& xContext )
818 {
819     static uno::Reference< beans::XPropertySet >  xPathSettings;
820     if ( !xPathSettings.is() )
821     {
822         uno::Reference< lang::XMultiComponentFactory > xSMgr( xContext->getServiceManager(), uno::UNO_QUERY_THROW );
823         xPathSettings.set( xSMgr->createInstanceWithContext(::rtl::OUString::createFromAscii("com.sun.star.util.PathSettings"), xContext), uno::UNO_QUERY_THROW );
824     }
825     return xPathSettings;
826 }
827 // MS Excel VBA: Returns the system path for the given path type.
828 // Status: implemented - uses UNO PathSettings service
getOfficePath(const rtl::OUString & _sPathType)829 rtl::OUString ScVbaApplication::getOfficePath( const rtl::OUString& _sPathType )
830 {
831     rtl::OUString sRetPath;
832     uno::Reference< beans::XPropertySet > xProps = lcl_getPathSettingsService( mxContext );
833     try
834     {
835         rtl::OUString sUrl;
836         xProps->getPropertyValue( _sPathType ) >>= sUrl;
837 
838         // if its a list of paths then use the last one
839         sal_Int32 nIndex =  sUrl.lastIndexOf( ';' ) ;
840         if ( nIndex > 0 )
841             sUrl = sUrl.copy( nIndex + 1 );
842         ::osl::File::getSystemPathFromFileURL( sUrl, sRetPath );
843     }
844     catch (uno::Exception&)
845     {
846         DebugHelper::exception(SbERR_METHOD_FAILED, rtl::OUString());
847     }
848     return sRetPath;
849 }
850 
851 // MS Excel VBA: Sets the default file path for saving files.
852 // Status: implemented - sets the "Work" path in UNO PathSettings
853 void SAL_CALL
setDefaultFilePath(const::rtl::OUString & DefaultFilePath)854 ScVbaApplication::setDefaultFilePath( const ::rtl::OUString& DefaultFilePath )
855 {
856     uno::Reference< beans::XPropertySet > xProps = lcl_getPathSettingsService( mxContext );
857     rtl::OUString aURL;
858     osl::FileBase::getFileURLFromSystemPath( DefaultFilePath, aURL );
859     xProps->setPropertyValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("Work")), uno::Any( aURL ) );
860 }
861 
862 // MS Excel VBA: Returns the default file path for saving files.
863 // Status: implemented - returns the "Work" path from UNO PathSettings
864 ::rtl::OUString SAL_CALL
getDefaultFilePath()865 ScVbaApplication::getDefaultFilePath()
866 {
867     return getOfficePath( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("Work")));
868 }
869 
870 // MS Excel VBA: Returns the path to the VBA library.
871 // Status: implemented - returns the "Basic" path from UNO PathSettings
872 ::rtl::OUString SAL_CALL
getLibraryPath()873 ScVbaApplication::getLibraryPath()
874 {
875     return getOfficePath( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("Basic")));
876 }
877 
878 // MS Excel VBA: Returns the path to the templates folder.
879 // Status: implemented - returns the "Template" path from UNO PathSettings
880 ::rtl::OUString SAL_CALL
getTemplatesPath()881 ScVbaApplication::getTemplatesPath()
882 {
883     return getOfficePath( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("Template")));
884 }
885 
886 // MS Excel VBA: Returns the platform-specific path separator character.
887 // Status: implemented - returns "/" on Unix, "\\" on Windows
888 ::rtl::OUString SAL_CALL
getPathSeparator()889 ScVbaApplication::getPathSeparator()
890 {
891     static rtl::OUString sPathSep( RTL_CONSTASCII_USTRINGPARAM( FILE_PATH_SEPERATOR ) );
892     return sPathSep;
893 }
894 
895 // ----------------------------------------------------------------------------
896 // Helpers for Intersect and Union
897 
898 namespace {
899 
900 typedef ::std::list< ScRange > ListOfScRange;
901 
902 /** Appends all ranges of a VBA Range object in the passed Any to the list of ranges. */
lclAddToListOfScRange(ListOfScRange & rList,const uno::Any & rArg)903 void lclAddToListOfScRange( ListOfScRange& rList, const uno::Any& rArg )
904 {
905     if( rArg.hasValue() )
906     {
907         uno::Reference< excel::XRange > xRange( rArg, uno::UNO_QUERY_THROW );
908         uno::Reference< XCollection > xCol( xRange->Areas( uno::Any() ), uno::UNO_QUERY_THROW );
909         for( sal_Int32 nIdx = 1, nCount = xCol->getCount(); nIdx <= nCount; ++nIdx )
910         {
911             uno::Reference< excel::XRange > xAreaRange( xCol->Item( uno::Any( nIdx ), uno::Any() ), uno::UNO_QUERY_THROW );
912             uno::Reference< sheet::XCellRangeAddressable > xAddressable( xAreaRange->getCellRange(), uno::UNO_QUERY_THROW );
913             ScRange aScRange;
914             ScUnoConversion::FillScRange( aScRange, xAddressable->getRangeAddress() );
915             rList.push_back( aScRange );
916         }
917     }
918 }
919 
920 /** Returns true, if the passed ranges can be expressed by a single range. The
921     new range will be contained in r1 then, the range r2 can be removed. */
lclTryJoin(ScRange & r1,const ScRange & r2)922 bool lclTryJoin( ScRange& r1, const ScRange& r2 )
923 {
924     // 1) r2 is completely inside r1
925     if( r1.In( r2 ) )
926         return true;
927 
928     // 2) r1 is completely inside r2
929     if( r2.In( r1 ) )
930     {
931         r1 = r2;
932         return true;
933     }
934 
935     SCCOL n1L = r1.aStart.Col();
936     SCCOL n1R = r1.aEnd.Col();
937     SCROW n1T = r1.aStart.Row();
938     SCROW n1B = r1.aEnd.Row();
939     SCCOL n2L = r2.aStart.Col();
940     SCCOL n2R = r2.aEnd.Col();
941     SCROW n2T = r2.aStart.Row();
942     SCROW n2B = r2.aEnd.Row();
943 
944     // 3) r1 and r2 have equal upper and lower border
945     if( (n1T == n2T) && (n1B == n2B) )
946     {
947         // check that r1 overlaps or touches r2
948         if( ((n1L < n2L) && (n2L - 1 <= n1R)) || ((n2L < n1L) && (n1L - 1 <= n2R)) )
949         {
950             r1.aStart.SetCol( ::std::min( n1L, n2L ) );
951             r1.aEnd.SetCol( ::std::max( n1R, n2R ) );
952             return true;
953         }
954         return false;
955     }
956 
957     // 4) r1 and r2 have equal left and right border
958     if( (n1L == n2L) && (n1R == n2R) )
959     {
960         // check that r1 overlaps or touches r2
961         if( ((n1T < n2T) && (n2T + 1 <= n1B)) || ((n2T < n1T) && (n1T + 1 <= n2B)) )
962         {
963             r1.aStart.SetRow( ::std::min( n1T, n2T ) );
964             r1.aEnd.SetRow( ::std::max( n1B, n2B ) );
965             return true;
966         }
967         return false;
968     }
969 
970     // 5) cannot join these ranges
971     return false;
972 }
973 
974 /** Strips out ranges that are contained by other ranges, joins ranges that can be joined
975     together (aligned borders, e.g. A4:D10 and B4:E10 would be combined to A4:E10. */
lclJoinRanges(ListOfScRange & rList)976 void lclJoinRanges( ListOfScRange& rList )
977 {
978     ListOfScRange::iterator aOuterIt = rList.begin();
979     while( aOuterIt != rList.end() )
980     {
981         bool bAnyErased = false;    // true = any range erased from rList
982         ListOfScRange::iterator aInnerIt = rList.begin();
983         while( aInnerIt != rList.end() )
984         {
985             bool bInnerErased = false;   // true = aInnerIt erased from rList
986             // do not compare a range with itself
987             if( (aOuterIt != aInnerIt) && lclTryJoin( *aOuterIt, *aInnerIt ) )
988             {
989                 // aOuterIt points to joined range, aInnerIt will be removed
990                 aInnerIt = rList.erase( aInnerIt );
991                 bInnerErased = bAnyErased = true;
992             }
993             /*  If aInnerIt has been erased from rList, it already points to
994                 the next element (return value of list::erase()). */
995             if( !bInnerErased )
996                 ++aInnerIt;
997         }
998         // if any range has been erased, repeat outer loop with the same range
999         if( !bAnyErased )
1000             ++aOuterIt;
1001     }
1002 }
1003 
1004 /** Intersects the passed list with all ranges of a VBA Range object in the passed Any. */
lclIntersectRanges(ListOfScRange & rList,const uno::Any & rArg)1005 void lclIntersectRanges( ListOfScRange& rList, const uno::Any& rArg )
1006 {
1007     // extract the ranges from the passed argument, will throw on invalid data
1008     ListOfScRange aList2;
1009     lclAddToListOfScRange( aList2, rArg );
1010     // do nothing, if the passed list is already empty
1011     if( !rList.empty() && !aList2.empty() )
1012     {
1013         // save original list in a local
1014         ListOfScRange aList1;
1015         aList1.swap( rList );
1016         // join ranges from passed argument
1017         lclJoinRanges( aList2 );
1018         // calculate intersection of the ranges in both lists
1019         for( ListOfScRange::const_iterator aOuterIt = aList1.begin(), aOuterEnd = aList1.end(); aOuterIt != aOuterEnd; ++aOuterIt )
1020         {
1021             for( ListOfScRange::const_iterator aInnerIt = aList2.begin(), aInnerEnd = aList2.end(); aInnerIt != aInnerEnd; ++aInnerIt )
1022             {
1023                 if( aOuterIt->Intersects( *aInnerIt ) )
1024                 {
1025                     ScRange aIsectRange(
1026                         Max( aOuterIt->aStart.Col(), aInnerIt->aStart.Col() ),
1027                         Max( aOuterIt->aStart.Row(), aInnerIt->aStart.Row() ),
1028                         Max( aOuterIt->aStart.Tab(), aInnerIt->aStart.Tab() ),
1029                         Min( aOuterIt->aEnd.Col(),   aInnerIt->aEnd.Col() ),
1030                         Min( aOuterIt->aEnd.Row(),   aInnerIt->aEnd.Row() ),
1031                         Min( aOuterIt->aEnd.Tab(),   aInnerIt->aEnd.Tab() ) );
1032                     rList.push_back( aIsectRange );
1033                 }
1034             }
1035         }
1036         // again, join the result ranges
1037         lclJoinRanges( rList );
1038     }
1039 }
1040 
1041 /** Creates a VBA Range object from the passed list of ranges. */
lclCreateVbaRange(const uno::Reference<uno::XComponentContext> & rxContext,const uno::Reference<frame::XModel> & rxModel,const ListOfScRange & rList)1042 uno::Reference< excel::XRange > lclCreateVbaRange(
1043         const uno::Reference< uno::XComponentContext >& rxContext,
1044         const uno::Reference< frame::XModel >& rxModel,
1045         const ListOfScRange& rList )
1046 {
1047     ScDocShell* pDocShell = excel::getDocShell( rxModel );
1048     if( !pDocShell ) throw uno::RuntimeException();
1049 
1050     ScRangeList aCellRanges;
1051     for( ListOfScRange::const_iterator aIt = rList.begin(), aEnd = rList.end(); aIt != aEnd; ++aIt )
1052         aCellRanges.Append( *aIt );
1053 
1054     if( aCellRanges.Count() == 1 )
1055     {
1056         uno::Reference< table::XCellRange > xRange( new ScCellRangeObj( pDocShell, *aCellRanges.First() ) );
1057         return new ScVbaRange( excel::getUnoSheetModuleObj( xRange ), rxContext, xRange );
1058     }
1059     if( aCellRanges.Count() > 1 )
1060     {
1061         uno::Reference< sheet::XSheetCellRangeContainer > xRanges( new ScCellRangesObj( pDocShell, aCellRanges ) );
1062         return new ScVbaRange( excel::getUnoSheetModuleObj( xRanges ), rxContext, xRanges );
1063     }
1064     return 0;
1065 }
1066 
1067 } // namespace
1068 
1069 // ----------------------------------------------------------------------------
1070 
1071 // MS Excel VBA: Returns the intersection of two or more ranges.
1072 // Status: implemented - handles up to 30 range arguments, joins and intersects
Intersect(const uno::Reference<excel::XRange> & rArg1,const uno::Reference<excel::XRange> & rArg2,const uno::Any & rArg3,const uno::Any & rArg4,const uno::Any & rArg5,const uno::Any & rArg6,const uno::Any & rArg7,const uno::Any & rArg8,const uno::Any & rArg9,const uno::Any & rArg10,const uno::Any & rArg11,const uno::Any & rArg12,const uno::Any & rArg13,const uno::Any & rArg14,const uno::Any & rArg15,const uno::Any & rArg16,const uno::Any & rArg17,const uno::Any & rArg18,const uno::Any & rArg19,const uno::Any & rArg20,const uno::Any & rArg21,const uno::Any & rArg22,const uno::Any & rArg23,const uno::Any & rArg24,const uno::Any & rArg25,const uno::Any & rArg26,const uno::Any & rArg27,const uno::Any & rArg28,const uno::Any & rArg29,const uno::Any & rArg30)1073 uno::Reference< excel::XRange > SAL_CALL ScVbaApplication::Intersect(
1074         const uno::Reference< excel::XRange >& rArg1, const uno::Reference< excel::XRange >& rArg2,
1075         const uno::Any& rArg3, const uno::Any& rArg4, const uno::Any& rArg5, const uno::Any& rArg6,
1076         const uno::Any& rArg7, const uno::Any& rArg8, const uno::Any& rArg9, const uno::Any& rArg10,
1077         const uno::Any& rArg11, const uno::Any& rArg12, const uno::Any& rArg13, const uno::Any& rArg14,
1078         const uno::Any& rArg15, const uno::Any& rArg16, const uno::Any& rArg17, const uno::Any& rArg18,
1079         const uno::Any& rArg19, const uno::Any& rArg20, const uno::Any& rArg21, const uno::Any& rArg22,
1080         const uno::Any& rArg23, const uno::Any& rArg24, const uno::Any& rArg25, const uno::Any& rArg26,
1081         const uno::Any& rArg27, const uno::Any& rArg28, const uno::Any& rArg29, const uno::Any& rArg30 )
1082 {
1083     if( !rArg1.is() || !rArg2.is() )
1084         DebugHelper::exception( SbERR_BAD_PARAMETER, rtl::OUString() );
1085 
1086     // initialize the result list with 1st parameter, join its ranges together
1087     ListOfScRange aList;
1088     lclAddToListOfScRange( aList, uno::Any( rArg1 ) );
1089     lclJoinRanges( aList );
1090 
1091     // process all other parameters, this updates the list with intersection
1092     lclIntersectRanges( aList, uno::Any( rArg2 ) );
1093     lclIntersectRanges( aList, rArg3 );
1094     lclIntersectRanges( aList, rArg4 );
1095     lclIntersectRanges( aList, rArg5 );
1096     lclIntersectRanges( aList, rArg6 );
1097     lclIntersectRanges( aList, rArg7 );
1098     lclIntersectRanges( aList, rArg8 );
1099     lclIntersectRanges( aList, rArg9 );
1100     lclIntersectRanges( aList, rArg10 );
1101     lclIntersectRanges( aList, rArg11 );
1102     lclIntersectRanges( aList, rArg12 );
1103     lclIntersectRanges( aList, rArg13 );
1104     lclIntersectRanges( aList, rArg14 );
1105     lclIntersectRanges( aList, rArg15 );
1106     lclIntersectRanges( aList, rArg16 );
1107     lclIntersectRanges( aList, rArg17 );
1108     lclIntersectRanges( aList, rArg18 );
1109     lclIntersectRanges( aList, rArg19 );
1110     lclIntersectRanges( aList, rArg20 );
1111     lclIntersectRanges( aList, rArg21 );
1112     lclIntersectRanges( aList, rArg22 );
1113     lclIntersectRanges( aList, rArg23 );
1114     lclIntersectRanges( aList, rArg24 );
1115     lclIntersectRanges( aList, rArg25 );
1116     lclIntersectRanges( aList, rArg26 );
1117     lclIntersectRanges( aList, rArg27 );
1118     lclIntersectRanges( aList, rArg28 );
1119     lclIntersectRanges( aList, rArg29 );
1120     lclIntersectRanges( aList, rArg30 );
1121 
1122     // create the VBA Range object
1123     return lclCreateVbaRange( mxContext, getCurrentDocument(), aList );
1124 }
1125 
1126 // MS Excel VBA: Returns the union of two or more ranges.
1127 // Status: implemented - handles up to 30 range arguments, joins all ranges
Union(const uno::Reference<excel::XRange> & rArg1,const uno::Reference<excel::XRange> & rArg2,const uno::Any & rArg3,const uno::Any & rArg4,const uno::Any & rArg5,const uno::Any & rArg6,const uno::Any & rArg7,const uno::Any & rArg8,const uno::Any & rArg9,const uno::Any & rArg10,const uno::Any & rArg11,const uno::Any & rArg12,const uno::Any & rArg13,const uno::Any & rArg14,const uno::Any & rArg15,const uno::Any & rArg16,const uno::Any & rArg17,const uno::Any & rArg18,const uno::Any & rArg19,const uno::Any & rArg20,const uno::Any & rArg21,const uno::Any & rArg22,const uno::Any & rArg23,const uno::Any & rArg24,const uno::Any & rArg25,const uno::Any & rArg26,const uno::Any & rArg27,const uno::Any & rArg28,const uno::Any & rArg29,const uno::Any & rArg30)1128 uno::Reference< excel::XRange > SAL_CALL ScVbaApplication::Union(
1129         const uno::Reference< excel::XRange >& rArg1, const uno::Reference< excel::XRange >& rArg2,
1130         const uno::Any& rArg3, const uno::Any& rArg4, const uno::Any& rArg5, const uno::Any& rArg6,
1131         const uno::Any& rArg7, const uno::Any& rArg8, const uno::Any& rArg9, const uno::Any& rArg10,
1132         const uno::Any& rArg11, const uno::Any& rArg12, const uno::Any& rArg13, const uno::Any& rArg14,
1133         const uno::Any& rArg15, const uno::Any& rArg16, const uno::Any& rArg17, const uno::Any& rArg18,
1134         const uno::Any& rArg19, const uno::Any& rArg20, const uno::Any& rArg21, const uno::Any& rArg22,
1135         const uno::Any& rArg23, const uno::Any& rArg24, const uno::Any& rArg25, const uno::Any& rArg26,
1136         const uno::Any& rArg27, const uno::Any& rArg28, const uno::Any& rArg29, const uno::Any& rArg30 )
1137 {
1138     if( !rArg1.is() || !rArg2.is() )
1139         DebugHelper::exception( SbERR_BAD_PARAMETER, rtl::OUString() );
1140 
1141     ListOfScRange aList;
1142     lclAddToListOfScRange( aList, uno::Any( rArg1 ) );
1143     lclAddToListOfScRange( aList, uno::Any( rArg2 ) );
1144     lclAddToListOfScRange( aList, rArg3 );
1145     lclAddToListOfScRange( aList, rArg4 );
1146     lclAddToListOfScRange( aList, rArg5 );
1147     lclAddToListOfScRange( aList, rArg6 );
1148     lclAddToListOfScRange( aList, rArg7 );
1149     lclAddToListOfScRange( aList, rArg8 );
1150     lclAddToListOfScRange( aList, rArg9 );
1151     lclAddToListOfScRange( aList, rArg10 );
1152     lclAddToListOfScRange( aList, rArg11 );
1153     lclAddToListOfScRange( aList, rArg12 );
1154     lclAddToListOfScRange( aList, rArg13 );
1155     lclAddToListOfScRange( aList, rArg14 );
1156     lclAddToListOfScRange( aList, rArg15 );
1157     lclAddToListOfScRange( aList, rArg16 );
1158     lclAddToListOfScRange( aList, rArg17 );
1159     lclAddToListOfScRange( aList, rArg18 );
1160     lclAddToListOfScRange( aList, rArg19 );
1161     lclAddToListOfScRange( aList, rArg20 );
1162     lclAddToListOfScRange( aList, rArg21 );
1163     lclAddToListOfScRange( aList, rArg22 );
1164     lclAddToListOfScRange( aList, rArg23 );
1165     lclAddToListOfScRange( aList, rArg24 );
1166     lclAddToListOfScRange( aList, rArg25 );
1167     lclAddToListOfScRange( aList, rArg26 );
1168     lclAddToListOfScRange( aList, rArg27 );
1169     lclAddToListOfScRange( aList, rArg28 );
1170     lclAddToListOfScRange( aList, rArg29 );
1171     lclAddToListOfScRange( aList, rArg30 );
1172 
1173     // simply join together all ranges as much as possible, strip out covered ranges etc.
1174     lclJoinRanges( aList );
1175 
1176     // create the VBA Range object
1177     return lclCreateVbaRange( mxContext, getCurrentDocument(), aList );
1178 }
1179 
1180 // MS Excel VBA: Marks a range as volatile (recalculated every time).
1181 // Status: implemented - accepts any value (the volatile flag is ignored)
1182 void
Volatile(const uno::Any & aVolatile)1183 ScVbaApplication::Volatile( const uno::Any& aVolatile )
1184 {
1185     sal_Bool bVolatile = sal_True;
1186     aVolatile >>= bVolatile;
1187     return;
1188 }
1189 
1190 // MS Excel VBA: Yields control to the operating system for event processing.
1191 // Status: implemented - currently a no-op
1192 void SAL_CALL
DoEvents()1193 ScVbaApplication::DoEvents()
1194 {
1195 }
1196 // MS Excel VBA: Returns whether the formula bar is displayed.
1197 // Status: implemented - queries the view shell for the input line toggle
1198 ::sal_Bool SAL_CALL
getDisplayFormulaBar()1199 ScVbaApplication::getDisplayFormulaBar()
1200 {
1201     sal_Bool bRes = sal_False;
1202     ScTabViewShell* pViewShell = excel::getCurrentBestViewShell( mxContext );
1203     if ( pViewShell )
1204     {
1205         SfxBoolItem sfxFormBar( FID_TOGGLEINPUTLINE);
1206         SfxAllItemSet reqList(  SFX_APP()->GetPool() );
1207         reqList.Put( sfxFormBar );
1208 
1209         pViewShell->GetState( reqList );
1210         const SfxPoolItem *pItem=0;
1211         if ( reqList.GetItemState( FID_TOGGLEINPUTLINE, sal_False, &pItem ) == SFX_ITEM_SET )
1212             bRes =   ((SfxBoolItem*)pItem)->GetValue();
1213     }
1214     return bRes;
1215 }
1216 
1217 // MS Excel VBA: Sets whether the formula bar is displayed.
1218 // Status: implemented - toggles via SfxRequest with FID_TOGGLEINPUTLINE
1219 void SAL_CALL
setDisplayFormulaBar(::sal_Bool _displayformulabar)1220 ScVbaApplication::setDisplayFormulaBar( ::sal_Bool _displayformulabar )
1221 {
1222     ScTabViewShell* pViewShell = excel::getCurrentBestViewShell( mxContext );
1223     if ( pViewShell && ( _displayformulabar !=  getDisplayFormulaBar() ) )
1224     {
1225         SfxBoolItem sfxFormBar( FID_TOGGLEINPUTLINE, _displayformulabar);
1226         SfxAllItemSet reqList(  SFX_APP()->GetPool() );
1227         SfxRequest aReq( FID_TOGGLEINPUTLINE, 0, reqList );
1228         pViewShell->Execute( aReq );
1229     }
1230 }
1231 
1232 // MS Excel VBA: Returns information about the caller of a macro or function.
1233 // Status: implemented - delegates to FuncCaller BASIC function
1234 uno::Any SAL_CALL
Caller(const uno::Any &)1235 ScVbaApplication::Caller( const uno::Any& /*aIndex*/ )
1236 {
1237     StarBASIC* pBasic = SFX_APP()->GetBasic();
1238     SbMethod* pMeth = (SbMethod*)pBasic->GetRtl()->Find( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("FuncCaller") ), SbxCLASS_METHOD );
1239     uno::Any aRet;
1240     if ( pMeth )
1241     {
1242         SbxVariableRef refTemp = pMeth;
1243         // forces a broadcast
1244         SbxVariableRef pNew = new  SbxMethod( *((SbxMethod*)pMeth));
1245                 OSL_TRACE("pNew has type %d and string value %s", pNew->GetType(), rtl::OUStringToOString( pNew->GetString(), RTL_TEXTENCODING_UTF8 ).getStr() );
1246         aRet = sbxToUnoValue( pNew );
1247     }
1248     return aRet;
1249 }
1250 
1251 // MS Excel VBA: Displays a dialog for opening files and returns the selected filename(s).
1252 // Status: implemented - uses ooo.vba.OpenFilePicker service
GetOpenFilename(const uno::Any & rFileFilter,const uno::Any & rFilterIndex,const uno::Any & rTitle,const uno::Any & rButtonText,const uno::Any & rMultiSelect)1253 uno::Any SAL_CALL ScVbaApplication::GetOpenFilename(
1254         const uno::Any& rFileFilter, const uno::Any& rFilterIndex, const uno::Any& rTitle,
1255         const uno::Any& rButtonText, const uno::Any& rMultiSelect )
1256 {
1257     uno::Sequence< uno::Any > aArgs( 6 );
1258     aArgs[ 0 ] <<= getThisExcelDoc( mxContext );
1259     aArgs[ 1 ] = rFileFilter;
1260     aArgs[ 2 ] = rFilterIndex;
1261     aArgs[ 3 ] = rTitle;
1262     aArgs[ 4 ] = rButtonText;
1263     aArgs[ 5 ] = rMultiSelect;
1264     uno::Reference< lang::XMultiComponentFactory > xFactory( mxContext->getServiceManager(), uno::UNO_SET_THROW );
1265     uno::Reference< XExecutableDialog > xFilePicker( xFactory->createInstanceWithArgumentsAndContext(
1266         ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "ooo.vba.OpenFilePicker" ) ), aArgs, mxContext ), uno::UNO_QUERY_THROW );
1267     return xFilePicker->execute();
1268 }
1269 
1270 // MS Excel VBA: Displays a dialog for saving files and returns the selected filename.
1271 // Status: implemented - uses ooo.vba.SaveAsFilePicker service
GetSaveAsFilename(const uno::Any & rInitialFileName,const uno::Any & rFileFilter,const uno::Any & rFilterIndex,const uno::Any & rTitle,const uno::Any & rButtonText)1272 uno::Any SAL_CALL ScVbaApplication::GetSaveAsFilename(
1273         const uno::Any& rInitialFileName, const uno::Any& rFileFilter, const uno::Any& rFilterIndex,
1274         const uno::Any& rTitle, const uno::Any& rButtonText )
1275 {
1276     uno::Sequence< uno::Any > aArgs( 6 );
1277     aArgs[ 0 ] <<= getThisExcelDoc( mxContext );
1278     aArgs[ 1 ] = rInitialFileName;
1279     aArgs[ 2 ] = rFileFilter;
1280     aArgs[ 3 ] = rFilterIndex;
1281     aArgs[ 4 ] = rTitle;
1282     aArgs[ 5 ] = rButtonText;
1283     uno::Reference< lang::XMultiComponentFactory > xFactory( mxContext->getServiceManager(), uno::UNO_SET_THROW );
1284     uno::Reference< XExecutableDialog > xFilePicker( xFactory->createInstanceWithArgumentsAndContext(
1285         ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "ooo.vba.SaveAsFilePicker" ) ), aArgs, mxContext ), uno::UNO_QUERY_THROW );
1286     return xFilePicker->execute();
1287 }
1288 
1289 // MS Excel VBA: Returns a FileDialog object for the specified dialog type.
1290 // Status: implemented - creates ScVbaFileDialog with the specified type
1291 uno::Reference< ooo::vba::XFileDialog > SAL_CALL
FileDialog(sal_Int32 nFileDialogType)1292 ScVbaApplication::FileDialog( sal_Int32 nFileDialogType )
1293 {
1294     uno::Reference< frame::XModel > xModel( getThisExcelDoc( mxContext ), uno::UNO_SET_THROW );
1295     uno::Reference< ooo::vba::XFileDialog > xFileDialog(
1296         new ScVbaFileDialog( this, mxContext, xModel ) );
1297     xFileDialog->setMsoFileDialogType( nFileDialogType );
1298     return xFileDialog;
1299 }
1300 
1301 // MS Excel VBA: Returns the FileSearch object for searching files on disk.
1302 // Status: implemented - creates ScVbaFileSearch
1303 uno::Reference< ooo::vba::XFileSearch > SAL_CALL
getFileSearch()1304 ScVbaApplication::getFileSearch()
1305 {
1306     uno::Reference< ooo::vba::XFileSearch > xFileSearch(
1307         new ScVbaFileSearch( this, this, mxContext ) );
1308     return xFileSearch;
1309 }
1310 
1311 // MS Excel VBA: Returns the current document model.
1312 // Status: implemented - delegates to excel::getCurrentExcelDoc
1313 uno::Reference< frame::XModel >
getCurrentDocument()1314 ScVbaApplication::getCurrentDocument()
1315 {
1316     return getCurrentExcelDoc(mxContext);
1317 }
1318 
1319 // MS Excel VBA: Counts non-empty cells in the given argument (COUNTA function).
1320 // Status: implemented - delegates to WorksheetFunction.CountA
1321 double SAL_CALL
CountA(const css::uno::Any & aArg1)1322 ScVbaApplication::CountA( const css::uno::Any& aArg1 )
1323 {
1324     double result = 0;
1325     uno::Reference< script::XInvocation > xInvoc( WorksheetFunction(), uno::UNO_QUERY_THROW );
1326     if ( xInvoc.is() )
1327     {
1328         static rtl::OUString FunctionName( RTL_CONSTASCII_USTRINGPARAM("CountA") );
1329         uno::Sequence< uno::Any > Params(1);
1330         Params[0] = aArg1;
1331         uno::Sequence< sal_Int16 > OutParamIndex;
1332         uno::Sequence< uno::Any > OutParam;
1333         xInvoc->invoke( FunctionName, Params, OutParamIndex, OutParam ) >>= result;
1334     }
1335     return result;
1336 }
1337 
1338 // MS Excel VBA: Returns the MenuBars collection.
1339 // Status: stubbed - returns empty Any
1340 uno::Any SAL_CALL
MenuBars(const css::uno::Any & aIndex)1341 ScVbaApplication::MenuBars( const css::uno::Any& aIndex )
1342 {
1343     return uno::Any();
1344 }
1345 
1346 // MS Excel VBA: Returns locale-specific information for the application.
1347 // Status: stubbed - returns empty Any
1348 uno::Any SAL_CALL
International(sal_Int32 nIndex)1349 ScVbaApplication::International( sal_Int32 nIndex )
1350 {
1351     // Excel Application.International() constants (XlApplicationInternational):
1352     // 1=xlCountryCode, 2=xlCountrySetting, 3=xlDecimalSeparator,
1353     // 4=xlThousandsSeparator, 5=xlListSeparator, 6=xlUpperCaseRowLetter,
1354     // 7=xlUpperCaseColumnLetter, 8=xlLowerCaseRowLetter, 9=xlLowerCaseColumnLetter,
1355     // 10=xlLeftBracket, 11=xlRightBracket, 12=xlLeftBrace, 13=xlRightBrace,
1356     // 14=xlColumnSeparator, 15=xlRowSeparator, 16=xlAlternateArraySeparator,
1357     // 17=xlDateSeparator, 18=xlTimeSeparator, 19=xlYearCode, 20=xlMonthCode,
1358     // 21=xlDayCode, 22=xlHourCode, 23=xlMinuteCode, 24=xlSecondCode,
1359     // 25=xlCurrencyCode, 26=xlGeneralFormatName, 27=xlCurrencyDigits,
1360     // 28=xlCurrencyNegative, 29=xlNoncurrencyDigits, 30=xlMonthNameChars,
1361     // 31=xlWeekdayNameChars, 32=xlDateOrder, 33=xl24HourClock,
1362     // 34=xlNonEnglishFunctions, 35=xlMetric, 37=xlCurrencyBefore,
1363     // 38=xlCurrencyMinusSign, 40=xlCurrencyLeadingZeros, 41=xlMonthLeadingZero,
1364     // 42=xlDayLeadingZero, 43=xl4DigitYears, 44=xlMDY, 45=xlTimeLeadingZero
1365 
1366     const SvtSysLocale aSysLocale;
1367     const LocaleDataWrapper& rLocaleData = aSysLocale.GetLocaleData();
1368 
1369     uno::Any aRet;
1370     switch ( nIndex )
1371     {
1372         case 1: // xlCountryCode
1373             aRet <<= rtl::OUString( rLocaleData.getLanguageCountryInfo().Country );
1374             break;
1375         case 2: // xlCountrySetting
1376             aRet <<= rtl::OUString( rLocaleData.getLanguageCountryInfo().Country );
1377             break;
1378         case 3: // xlDecimalSeparator
1379             aRet <<= rtl::OUString( rLocaleData.getNumDecimalSep() );
1380             break;
1381         case 4: // xlThousandsSeparator
1382             aRet <<= rtl::OUString( rLocaleData.getNumThousandSep() );
1383             break;
1384         case 5: // xlListSeparator
1385             aRet <<= rtl::OUString( rLocaleData.getListSep() );
1386             break;
1387         case 6: // xlUpperCaseRowLetter
1388             aRet <<= rtl::OUString::createFromAscii( "R" );
1389             break;
1390         case 7: // xlUpperCaseColumnLetter
1391             aRet <<= rtl::OUString::createFromAscii( "C" );
1392             break;
1393         case 8: // xlLowerCaseRowLetter
1394             aRet <<= rtl::OUString::createFromAscii( "r" );
1395             break;
1396         case 9: // xlLowerCaseColumnLetter
1397             aRet <<= rtl::OUString::createFromAscii( "c" );
1398             break;
1399         case 10: // xlLeftBracket
1400             aRet <<= rtl::OUString::createFromAscii( "[" );
1401             break;
1402         case 11: // xlRightBracket
1403             aRet <<= rtl::OUString::createFromAscii( "]" );
1404             break;
1405         case 12: // xlLeftBrace
1406             aRet <<= rtl::OUString::createFromAscii( "{" );
1407             break;
1408         case 13: // xlRightBrace
1409             aRet <<= rtl::OUString::createFromAscii( "}" );
1410             break;
1411         case 14: // xlColumnSeparator
1412             aRet <<= rtl::OUString( rLocaleData.getListSep() );
1413             break;
1414         case 15: // xlRowSeparator
1415             aRet <<= rtl::OUString::createFromAscii( "~" );
1416             break;
1417         case 16: // xlAlternateArraySeparator
1418             aRet <<= rtl::OUString( rLocaleData.getListSep() );
1419             break;
1420         case 17: // xlDateSeparator
1421             aRet <<= rtl::OUString( rLocaleData.getDateSep() );
1422             break;
1423         case 18: // xlTimeSeparator
1424             aRet <<= rtl::OUString( rLocaleData.getTimeSep() );
1425             break;
1426         case 19: // xlYearCode
1427             aRet <<= rtl::OUString::createFromAscii( "y" );
1428             break;
1429         case 20: // xlMonthCode
1430             aRet <<= rtl::OUString::createFromAscii( "m" );
1431             break;
1432         case 21: // xlDayCode
1433             aRet <<= rtl::OUString::createFromAscii( "d" );
1434             break;
1435         case 22: // xlHourCode
1436             aRet <<= rtl::OUString::createFromAscii( "h" );
1437             break;
1438         case 23: // xlMinuteCode
1439             aRet <<= rtl::OUString::createFromAscii( "m" );
1440             break;
1441         case 24: // xlSecondCode
1442             aRet <<= rtl::OUString::createFromAscii( "s" );
1443             break;
1444         case 25: // xlCurrencyCode
1445             aRet <<= rtl::OUString( rLocaleData.getCurrSymbol() );
1446             break;
1447         case 26: // xlGeneralFormatName
1448             aRet <<= rtl::OUString::createFromAscii( "General" );
1449             break;
1450         case 27: // xlCurrencyDigits
1451             aRet <<= sal_Int32( rLocaleData.getCurrDigits() );
1452             break;
1453         case 33: // xl24HourClock
1454             aRet <<= sal_Bool( false );
1455             break;
1456         case 35: // xlMetric
1457             aRet <<= sal_Bool( rLocaleData.getMeasurementSystemEnum() == MEASURE_METRIC );
1458             break;
1459         case 43: // xl4DigitYears
1460             aRet <<= sal_Bool( true );
1461             break;
1462         case 44: // xlMDY
1463             aRet <<= sal_Bool( rLocaleData.getDateFormat() == MDY );
1464             break;
1465         default:
1466             DebugHelper::exception( SbERR_BAD_PARAMETER, rtl::OUString() );
1467             break;
1468     }
1469     return aRet;
1470 }
1471 
1472 // MS Excel VBA: Undoes the last user action.
1473 // Status: stubbed - no-op
1474 void SAL_CALL
Undo()1475 ScVbaApplication::Undo()
1476 {
1477     try
1478     {
1479         ScTabViewShell* pViewShell = excel::getCurrentBestViewShell(mxContext);
1480         if ( !pViewShell )
1481             throw uno::RuntimeException( rtl::OUString::createFromAscii("No ViewShell available"), uno::Reference< uno::XInterface >() );
1482 
1483         ::svl::IUndoManager* pUndoManager = pViewShell->GetViewData()->GetDocShell()->GetUndoManager();
1484         if ( pUndoManager && pUndoManager->GetUndoActionCount() > 0 )
1485             pUndoManager->Undo();
1486     }
1487      catch( const uno::Exception& )
1488      {
1489          DebugHelper::exception(SbERR_METHOD_FAILED, rtl::OUString() );
1490      }
1491 }
1492 
1493 // MS Excel VBA: Runs a macro by name, optionally with arguments.
1494 // Status: implemented - uses XScriptProvider to invoke the named macro
1495 uno::Any SAL_CALL
Run(const rtl::OUString & rMacroName,const uno::Any & Arg1,const uno::Any & Arg2,const uno::Any & Arg3,const uno::Any & Arg4,const uno::Any & Arg5)1496 ScVbaApplication::Run( const rtl::OUString& rMacroName, const uno::Any& Arg1, const uno::Any& Arg2, const uno::Any& Arg3, const uno::Any& Arg4, const uno::Any& Arg5 )
1497 {
1498     uno::Any aResult;
1499     try
1500     {
1501         // Get the script provider from the document model
1502         uno::Reference< frame::XModel > xModel( getCurrentDocument() );
1503         if( !xModel.is() )
1504             throw script::BasicErrorException( ::rtl::OUString(), uno::Reference< uno::XInterface >(), 1000, ::rtl::OUString() );
1505 
1506         uno::Reference< script::provider::XScriptProviderSupplier > xSPSupplier( xModel, uno::UNO_QUERY_THROW );
1507         uno::Reference< script::provider::XScriptProvider > xScriptProvider = xSPSupplier->getScriptProvider();
1508         if( !xScriptProvider.is() )
1509             throw script::BasicErrorException( ::rtl::OUString(), uno::Reference< uno::XInterface >(), 1000, ::rtl::OUString() );
1510 
1511         // Build the script URI
1512         rtl::OUString sScriptURI = rtl::OUString::createFromAscii("vnd.sun.star.script:Standard.") + rMacroName +
1513             rtl::OUString::createFromAscii("?language=Basic&location=document");
1514 
1515         // Get the script
1516         uno::Reference< script::provider::XScript > xScript = xScriptProvider->getScript( sScriptURI );
1517         if( !xScript.is() )
1518             throw script::BasicErrorException( ::rtl::OUString(), uno::Reference< uno::XInterface >(), 1000, ::rtl::OUString() );
1519 
1520         // Build arguments array (filter out empty/void arguments)
1521         std::vector<uno::Any> args;
1522         if( Arg1.hasValue() ) args.push_back(Arg1);
1523         if( Arg2.hasValue() ) args.push_back(Arg2);
1524         if( Arg3.hasValue() ) args.push_back(Arg3);
1525         if( Arg4.hasValue() ) args.push_back(Arg4);
1526         if( Arg5.hasValue() ) args.push_back(Arg5);
1527 
1528         uno::Sequence<uno::Any> scriptArgs( args.size() );
1529         for( size_t i = 0; i < args.size(); ++i )
1530             scriptArgs[i] = args[i];
1531 
1532         // Invoke the script
1533         uno::Sequence<sal_Int16> outParamIndex;
1534         uno::Sequence<uno::Any> outParams;
1535         aResult = xScript->invoke( scriptArgs, outParamIndex, outParams );
1536     }
1537     catch( const uno::Exception& )
1538     {
1539         aResult <<= script::BasicErrorException( ::rtl::OUString(), uno::Reference< uno::XInterface >(), 1000, ::rtl::OUString() );
1540     }
1541     return aResult;
1542 }
1543 
1544 double SAL_CALL
InchesToPoints(double nInches)1545 ScVbaApplication::InchesToPoints( double nInches )
1546 {
1547     return nInches * 72.0;
1548 }
1549 
1550 // MS Excel VBA: Returns the number of sheets in new workbooks.
1551 // Status: implemented - reads from ScAppOptions
getSheetsInNewWorkbook()1552 sal_Int32 SAL_CALL ScVbaApplication::getSheetsInNewWorkbook()
1553 {
1554     // AOO always creates 1 sheet per new spreadsheet
1555     return 1;
1556 }
1557 
1558 // MS Excel VBA: Sets the number of sheets in new workbooks.
1559 // Status: implemented - validates range (1-255) and sets in ScAppOptions
setSheetsInNewWorkbook(sal_Int32 nSheets)1560 void SAL_CALL ScVbaApplication::setSheetsInNewWorkbook( sal_Int32 nSheets )
1561 {
1562     // AOO's default behavior creates 1 sheet per new spreadsheet;
1563     // this is not configurable via ScAppOptions. Silently ignore.
1564     if ( nSheets < 1 || nSheets > MAXTAB )
1565     {
1566         DebugHelper::exception( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("The number must be between 1 and 255") ), uno::Exception(), SbERR_METHOD_FAILED, rtl::OUString() );
1567     }
1568     else
1569     {
1570         ScAppOptions& rAppOpt = const_cast< ScAppOptions& >(SC_MOD()->GetAppOptions());
1571         rAppOpt.SetTabCountInNewSpreadsheet( static_cast<sal_uInt16>(nSheets) );
1572     }
1573 }
1574 
1575 // MS Excel VBA: Returns the implementation name of this service.
1576 // Status: implemented - returns "ScVbaApplication"
1577 rtl::OUString&
getServiceImplName()1578 ScVbaApplication::getServiceImplName()
1579 {
1580     static rtl::OUString sImplName( RTL_CONSTASCII_USTRINGPARAM("ScVbaApplication") );
1581     return sImplName;
1582 }
1583 
1584 // MS Excel VBA: Returns the service names supported by this implementation.
1585 // Status: implemented - returns "ooo.vba.excel.Application"
1586 uno::Sequence< rtl::OUString >
getServiceNames()1587 ScVbaApplication::getServiceNames()
1588 {
1589     static uno::Sequence< rtl::OUString > aServiceNames;
1590     if ( aServiceNames.getLength() == 0 )
1591     {
1592         aServiceNames.realloc( 1 );
1593         aServiceNames[ 0 ] = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("ooo.vba.excel.Application" ) );
1594     }
1595     return aServiceNames;
1596 }
1597 
1598 namespace application
1599 {
1600 namespace sdecl = comphelper::service_decl;
1601 sdecl::vba_service_class_<ScVbaApplication, sdecl::with_args<false> > serviceImpl;
1602 extern sdecl::ServiceDecl const serviceDecl(
1603     serviceImpl,
1604     "ScVbaApplication",
1605     "ooo.vba.excel.Application" );
1606 }
1607