bump product version to 4.1.6.2
[LibreOffice.git] / sc / source / ui / vba / vbaworkbooks.cxx
blob5198fc8b53ff1349e512c572907d847340d6a70d
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3 * This file is part of the LibreOffice project.
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
9 * This file incorporates work covered by the following license notice:
11 * Licensed to the Apache Software Foundation (ASF) under one or more
12 * contributor license agreements. See the NOTICE file distributed
13 * with this work for additional information regarding copyright
14 * ownership. The ASF licenses this file to you under the Apache
15 * License, Version 2.0 (the "License"); you may not use this file
16 * except in compliance with the License. You may obtain a copy of
17 * the License at http://www.apache.org/licenses/LICENSE-2.0 .
19 #include <comphelper/processfactory.hxx>
21 #include <cppuhelper/implbase1.hxx>
22 #include <cppuhelper/implbase3.hxx>
24 #include <com/sun/star/frame/XDesktop.hpp>
25 #include <com/sun/star/sheet/XSpreadsheetDocument.hpp>
26 #include <com/sun/star/container/XEnumerationAccess.hpp>
27 #include <com/sun/star/frame/XComponentLoader.hpp>
28 #include <com/sun/star/lang/XComponent.hpp>
29 #include <com/sun/star/frame/XModel.hpp>
30 #include <com/sun/star/frame/XFrame.hpp>
31 #include <com/sun/star/frame/FrameSearchFlag.hpp>
32 #include <com/sun/star/util/XModifiable.hpp>
33 #include <com/sun/star/frame/XStorable.hpp>
34 #include <com/sun/star/lang/DisposedException.hpp>
35 #include <com/sun/star/beans/PropertyVetoException.hpp>
36 #include <com/sun/star/util/XCloseable.hpp>
37 #include <com/sun/star/lang/IndexOutOfBoundsException.hpp>
38 #include <com/sun/star/document/XTypeDetection.hpp>
39 #include <com/sun/star/uri/XUriReference.hpp>
40 #include <com/sun/star/uri/XUriReferenceFactory.hpp>
41 #include <com/sun/star/script/vba/VBAEventId.hpp>
42 #include <com/sun/star/script/vba/XVBACompatibility.hpp>
43 #include <com/sun/star/script/vba/XVBAEventProcessor.hpp>
44 #include <com/sun/star/script/vba/XVBAModuleInfo.hpp>
45 #include <com/sun/star/script/ModuleInfo.hpp>
46 #include <com/sun/star/script/ModuleType.hpp>
48 #include <sfx2/objsh.hxx>
49 #include <tools/urlobj.hxx>
51 #include "vbaglobals.hxx"
52 #include "vbaworkbook.hxx"
53 #include "vbaworkbooks.hxx"
54 #include <vbahelper/vbahelper.hxx>
56 #include <boost/unordered_map.hpp>
57 #include <vector>
58 #include <osl/file.hxx>
59 using namespace ::ooo::vba;
60 using namespace ::com::sun::star;
62 const sal_Int16 CUSTOM_CHAR = 5;
64 void setUpDocumentModules( const uno::Reference< sheet::XSpreadsheetDocument >& xDoc )
66 uno::Reference< frame::XModel > xModel( xDoc, uno::UNO_QUERY );
67 ScDocShell* pShell = excel::getDocShell( xModel );
68 if ( pShell )
70 String aPrjName( RTL_CONSTASCII_USTRINGPARAM( "Standard" ) );
71 pShell->GetBasicManager()->SetName( aPrjName );
73 /* Set library container to VBA compatibility mode. This will create
74 the VBA Globals object and store it in the Basic manager of the
75 document. */
76 uno::Reference<script::XLibraryContainer> xLibContainer = pShell->GetBasicContainer();
77 uno::Reference<script::vba::XVBACompatibility> xVBACompat( xLibContainer, uno::UNO_QUERY_THROW );
78 xVBACompat->setVBACompatibilityMode( sal_True );
80 if( xLibContainer.is() )
82 if( !xLibContainer->hasByName( aPrjName ) )
83 xLibContainer->createLibrary( aPrjName );
84 uno::Any aLibAny = xLibContainer->getByName( aPrjName );
85 uno::Reference< container::XNameContainer > xLib;
86 aLibAny >>= xLib;
87 if( xLib.is() )
89 uno::Reference< script::vba::XVBAModuleInfo > xVBAModuleInfo( xLib, uno::UNO_QUERY_THROW );
90 uno::Reference< lang::XMultiServiceFactory> xSF( pShell->GetModel(), uno::UNO_QUERY_THROW);
91 uno::Reference< container::XNameAccess > xVBACodeNamedObjectAccess( xSF->createInstance( OUString( "ooo.vba.VBAObjectModuleObjectProvider")), uno::UNO_QUERY_THROW );
92 // set up the module info for the workbook and sheets in the nealy created
93 // spreadsheet
94 ScDocument* pDoc = pShell->GetDocument();
95 String sCodeName = pDoc->GetCodeName();
96 if ( sCodeName.Len() == 0 )
98 sCodeName = String( RTL_CONSTASCII_USTRINGPARAM("ThisWorkbook") );
99 pDoc->SetCodeName( sCodeName );
102 std::vector< OUString > sDocModuleNames;
103 sDocModuleNames.push_back( sCodeName );
105 uno::Reference<container::XNameAccess > xSheets( xDoc->getSheets(), uno::UNO_QUERY_THROW );
106 uno::Sequence< OUString > sSheets( xSheets->getElementNames() );
108 for ( sal_Int32 index=0; index < sSheets.getLength() ; ++index )
110 sDocModuleNames.push_back( sSheets[ index ] );
113 std::vector<OUString>::iterator it_end = sDocModuleNames.end();
115 for ( std::vector<OUString>::iterator it = sDocModuleNames.begin(); it != it_end; ++it )
117 script::ModuleInfo sModuleInfo;
119 sModuleInfo.ModuleObject.set( xVBACodeNamedObjectAccess->getByName( *it ), uno::UNO_QUERY );
120 sModuleInfo.ModuleType = script::ModuleType::DOCUMENT;
121 xVBAModuleInfo->insertModuleInfo( *it, sModuleInfo );
122 if( xLib->hasByName( *it ) )
123 xLib->replaceByName( *it, uno::makeAny( OUString( "Option VBASupport 1\n") ) );
124 else
125 xLib->insertByName( *it, uno::makeAny( OUString( "Option VBASupport 1\n" ) ) );
132 static uno::Any
133 getWorkbook( uno::Reference< uno::XComponentContext >& xContext, const uno::Reference< sheet::XSpreadsheetDocument > &xDoc, const uno::Reference< XHelperInterface >& xParent )
135 // FIXME: fine as long as ScVbaWorkbook is stateless ...
136 uno::Reference< frame::XModel > xModel( xDoc, uno::UNO_QUERY );
137 if( !xModel.is() )
138 return uno::Any();
140 uno::Reference< excel::XWorkbook > xWb( getVBADocument( xModel ), uno::UNO_QUERY );
141 if ( xWb.is() )
143 OSL_TRACE(" *** Returning Module uno Object *** ");
144 return uno::Any( xWb );
147 ScVbaWorkbook *pWb = new ScVbaWorkbook( xParent, xContext, xModel );
148 return uno::Any( uno::Reference< excel::XWorkbook > (pWb) );
151 class WorkBookEnumImpl : public EnumerationHelperImpl
153 uno::Any m_aApplication;
154 public:
155 WorkBookEnumImpl( const uno::Reference< XHelperInterface >& xParent, const uno::Reference< uno::XComponentContext >& xContext, const uno::Reference< container::XEnumeration >& xEnumeration, const uno::Any& aApplication ) throw ( uno::RuntimeException ) : EnumerationHelperImpl( xParent, xContext, xEnumeration ), m_aApplication( aApplication ) {}
157 virtual uno::Any SAL_CALL nextElement( ) throw (container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException)
159 uno::Reference< sheet::XSpreadsheetDocument > xDoc( m_xEnumeration->nextElement(), uno::UNO_QUERY_THROW );
160 return getWorkbook( m_xContext, xDoc, m_xParent );
165 ScVbaWorkbooks::ScVbaWorkbooks( const uno::Reference< XHelperInterface >& xParent, const uno::Reference< css::uno::XComponentContext >& xContext ) : ScVbaWorkbooks_BASE( xParent, xContext, VbaDocumentsBase::EXCEL_DOCUMENT )
168 // XEnumerationAccess
169 uno::Type
170 ScVbaWorkbooks::getElementType() throw (uno::RuntimeException)
172 return excel::XWorkbook::static_type(0);
174 uno::Reference< container::XEnumeration >
175 ScVbaWorkbooks::createEnumeration() throw (uno::RuntimeException)
177 // #FIXME its possible the WorkBookEnumImpl here doens't reflect
178 // the state of this object ( although it should ) would be
179 // safer to create an enumeration based on this objects state
180 // rather than one effectively based of the desktop component
181 uno::Reference< container::XEnumerationAccess > xEnumerationAccess( m_xIndexAccess, uno::UNO_QUERY_THROW );
182 return new WorkBookEnumImpl( mxParent, mxContext, xEnumerationAccess->createEnumeration(), Application() );
185 uno::Any
186 ScVbaWorkbooks::createCollectionObject( const css::uno::Any& aSource )
188 uno::Reference< sheet::XSpreadsheetDocument > xDoc( aSource, uno::UNO_QUERY_THROW );
189 return getWorkbook( mxContext, xDoc, mxParent );
193 uno::Any SAL_CALL
194 ScVbaWorkbooks::Add( const uno::Any& Template ) throw (uno::RuntimeException)
196 uno::Reference< sheet::XSpreadsheetDocument > xSpreadDoc;
197 sal_Int32 nWorkbookType = 0;
198 OUString aTemplateFileName;
199 if( Template >>= nWorkbookType )
201 // nWorkbookType is a constant from XlWBATemplate (added in Excel 2007)
202 // TODO: create chart-sheet if supported by Calc
204 xSpreadDoc.set( createDocument(), uno::UNO_QUERY_THROW );
205 // create a document with one sheet only
206 uno::Reference< sheet::XSpreadsheets > xSheets( xSpreadDoc->getSheets(), uno::UNO_SET_THROW );
207 uno::Reference< container::XIndexAccess > xSheetsIA( xSheets, uno::UNO_QUERY_THROW );
208 while( xSheetsIA->getCount() > 1 )
210 uno::Reference< container::XNamed > xSheetName( xSheetsIA->getByIndex( xSheetsIA->getCount() - 1 ), uno::UNO_QUERY_THROW );
211 xSheets->removeByName( xSheetName->getName() );
214 else if( Template >>= aTemplateFileName )
216 // TODO: create document from template
217 xSpreadDoc.set( createDocument(), uno::UNO_QUERY_THROW );
219 else if( !Template.hasValue() )
221 // regular spreadsheet document with configured number of sheets
222 xSpreadDoc.set( createDocument(), uno::UNO_QUERY_THROW );
224 else
226 // illegal argument
227 throw uno::RuntimeException();
230 // need to set up the document modules ( and vba mode ) here
231 excel::setUpDocumentModules( xSpreadDoc );
232 if( xSpreadDoc.is() )
233 return getWorkbook( mxContext, xSpreadDoc, mxParent );
234 return uno::Any();
237 void SAL_CALL
238 ScVbaWorkbooks::Close() throw (uno::RuntimeException)
240 closeDocuments();
243 bool
244 ScVbaWorkbooks::isTextFile( const OUString& sType )
246 // will return true if the file is
247 // a) a variant of a text file
248 // b) a csv file
249 // c) unknown
250 // returning true basically means treat this like a csv file
251 const static OUString txtType("generic_Text");
252 return sType.equals( txtType ) || sType.isEmpty();
255 bool
256 ScVbaWorkbooks::isSpreadSheetFile( const OUString& sType )
258 // include calc_QPro etc. ? ( not for the moment anyway )
259 if ( sType.indexOf( "calc_MS" ) == 0
260 || sType.indexOf( "calc8" ) == 0
261 || sType.indexOf( "calc_StarOffice" ) == 0 )
262 return true;
263 return false;
266 OUString
267 ScVbaWorkbooks::getFileFilterType( const OUString& rFileName )
269 uno::Reference< document::XTypeDetection > xTypeDetect( mxContext->getServiceManager()->createInstanceWithContext(OUString("com.sun.star.document.TypeDetection"), mxContext), uno::UNO_QUERY_THROW );
270 uno::Sequence< beans::PropertyValue > aMediaDesc(1);
271 aMediaDesc[ 0 ].Name = OUString("URL" );
272 aMediaDesc[ 0 ].Value <<= rFileName;
273 OUString sType = xTypeDetect->queryTypeByDescriptor( aMediaDesc, sal_True );
274 return sType;
277 // #TODO# #FIXME# can any of the unused params below be used?
278 uno::Any SAL_CALL
279 ScVbaWorkbooks::Open( const OUString& rFileName, const uno::Any& /*UpdateLinks*/, const uno::Any& ReadOnly, const uno::Any& Format, const uno::Any& /*Password*/, const uno::Any& /*WriteResPassword*/, const uno::Any& /*IgnoreReadOnlyRecommended*/, const uno::Any& /*Origin*/, const uno::Any& Delimiter, const uno::Any& /*Editable*/, const uno::Any& /*Notify*/, const uno::Any& /*Converter*/, const uno::Any& /*AddToMru*/ ) throw (uno::RuntimeException)
281 // we need to detect if this is a URL, if not then assume its a file path
282 OUString aURL;
283 INetURLObject aObj;
284 aObj.SetURL( rFileName );
285 bool bIsURL = aObj.GetProtocol() != INET_PROT_NOT_VALID;
286 if ( bIsURL )
287 aURL = rFileName;
288 else
289 osl::FileBase::getFileURLFromSystemPath( rFileName, aURL );
291 uno::Sequence< beans::PropertyValue > sProps(0);
293 OUString sType = getFileFilterType( aURL );
294 // A text file means it needs to be processed as a csv file
295 if ( isTextFile( sType ) )
297 sal_Int32 nIndex = 0;
298 // Values for format
299 // 1 Tabs
300 // 2 Commas
301 // 3 Spaces
302 // 4 Semicolons
303 // 5 Nothing
304 // 6 Custom character (see the Delimiter argument
305 // no format means use the current delimiter
306 sProps.realloc( 3 );
307 sProps[ nIndex ].Name = OUString("FilterOptions" );
308 sal_Int16 delims[] = { 0 /*default not used*/, 9/*tab*/, 44/*comma*/, 32/*space*/, 59/*semicolon*/ };
309 static OUString sRestOfFormat(",34,0,1" );
311 OUString sFormat;
312 sal_Int16 nFormat = 0; // default indicator
315 if ( Format.hasValue() )
317 Format >>= nFormat; // val of nFormat overwritten if extracted
318 // validate param
319 if ( nFormat < 1 || nFormat > 6 )
320 throw uno::RuntimeException( OUString( "Illegal value for Format" ), uno::Reference< uno::XInterface >() );
323 sal_Int16 nDelim = getCurrentDelim();
325 if ( nFormat > 0 && nFormat < CUSTOM_CHAR )
327 nDelim = delims[ nFormat ];
329 else if ( nFormat > CUSTOM_CHAR )
331 // Need to check Delimiter param
332 if ( !Delimiter.hasValue() )
333 throw uno::RuntimeException( OUString( "Expected value for Delimiter" ), uno::Reference< uno::XInterface >() );
334 OUString sStr;
335 Delimiter >>= sStr;
336 String aUniStr( sStr );
337 if ( aUniStr.Len() )
338 nDelim = aUniStr.GetChar(0);
339 else
340 throw uno::RuntimeException( OUString( "Incorrect value for Delimiter" ), uno::Reference< uno::XInterface >() );
343 getCurrentDelim() = nDelim; //set new current
345 sFormat = OUString::valueOf( (sal_Int32)nDelim ) + sRestOfFormat;
346 sProps[ nIndex++ ].Value <<= sFormat;
347 sProps[ nIndex ].Name = OUString("FilterName");
348 sProps[ nIndex++ ].Value <<= OUString( "Text - txt - csv (StarCalc)" );
349 // Ensure WORKAROUND_CSV_TXT_BUG_i60158 gets called in typedetection.cxx so
350 // csv is forced for deep detected 'writerxxx' types
351 sProps[ nIndex ].Name = OUString("DocumentService");
352 sProps[ nIndex ].Value <<= OUString("com.sun.star.sheet.SpreadsheetDocument");
354 else if ( !isSpreadSheetFile( sType ) )
355 throw uno::RuntimeException( OUString("Bad Format"), uno::Reference< uno::XInterface >() );
357 uno::Reference <sheet::XSpreadsheetDocument> xSpreadDoc( openDocument( rFileName, ReadOnly, sProps ), uno::UNO_QUERY_THROW );
358 uno::Any aRet = getWorkbook( mxContext, xSpreadDoc, mxParent );
359 uno::Reference< excel::XWorkbook > xWBook( aRet, uno::UNO_QUERY );
360 if ( xWBook.is() )
361 xWBook->Activate();
362 return aRet;
365 OUString
366 ScVbaWorkbooks::getServiceImplName()
368 return OUString("ScVbaWorkbooks");
371 css::uno::Sequence<OUString>
372 ScVbaWorkbooks::getServiceNames()
374 static uno::Sequence< OUString > sNames;
375 if ( sNames.getLength() == 0 )
377 sNames.realloc( 1 );
378 sNames[0] = OUString("ooo.vba.excel.Workbooks");
380 return sNames;
383 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */