LibreOffice Module sc (master)  1
vbaworkbooks.cxx
Go to the documentation of this file.
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3  * This file is part of the LibreOffice project.
4  *
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/.
8  *
9  * This file incorporates work covered by the following license notice:
10  *
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 .
18  */
19 
20 #include <com/sun/star/sheet/XSpreadsheetDocument.hpp>
21 #include <com/sun/star/container/XEnumerationAccess.hpp>
22 #include <com/sun/star/frame/XModel.hpp>
23 #include <com/sun/star/uno/XComponentContext.hpp>
24 #include <com/sun/star/document/XTypeDetection.hpp>
25 
26 #include <tools/urlobj.hxx>
27 
28 #include "excelvbahelper.hxx"
29 #include "vbaworkbook.hxx"
30 #include "vbaworkbooks.hxx"
31 #include <vbahelper/vbahelper.hxx>
32 
33 #include <o3tl/string_view.hxx>
34 #include <osl/file.hxx>
35 #include <rtl/ref.hxx>
36 
37 using namespace ::ooo::vba;
38 using namespace ::com::sun::star;
39 
40 const sal_Int16 CUSTOM_CHAR = 5;
41 
42 static uno::Any
43 getWorkbook( const uno::Reference< uno::XComponentContext >& xContext,
44  const uno::Reference< sheet::XSpreadsheetDocument > &xDoc,
45  const uno::Reference< XHelperInterface >& xParent )
46 {
47  // FIXME: fine as long as ScVbaWorkbook is stateless ...
48  uno::Reference< frame::XModel > xModel( xDoc, uno::UNO_QUERY );
49  if( !xModel.is() )
50  return uno::Any();
51 
52  uno::Reference< excel::XWorkbook > xWb( getVBADocument( xModel ), uno::UNO_QUERY );
53  if ( xWb.is() )
54  {
55  return uno::Any( xWb );
56  }
57 
58  rtl::Reference<ScVbaWorkbook> pWb = new ScVbaWorkbook( xParent, xContext, xModel );
59  return uno::Any( uno::Reference< excel::XWorkbook > (pWb) );
60 }
61 
62 namespace {
63 
64 class WorkBookEnumImpl : public EnumerationHelperImpl
65 {
66 public:
68  WorkBookEnumImpl( const uno::Reference< XHelperInterface >& xParent, const uno::Reference< uno::XComponentContext >& xContext, const uno::Reference< container::XEnumeration >& xEnumeration ) : EnumerationHelperImpl( xParent, xContext, xEnumeration ) {}
69 
70  virtual uno::Any SAL_CALL nextElement( ) override
71  {
72  uno::Reference< sheet::XSpreadsheetDocument > xDoc( m_xEnumeration->nextElement(), uno::UNO_QUERY_THROW );
73  return getWorkbook( m_xContext, xDoc, m_xParent );
74  }
75 
76 };
77 
78 }
79 
80 ScVbaWorkbooks::ScVbaWorkbooks( const uno::Reference< XHelperInterface >& xParent, const uno::Reference< css::uno::XComponentContext >& xContext ) : ScVbaWorkbooks_BASE( xParent, xContext, VbaDocumentsBase::EXCEL_DOCUMENT )
81 {
82 }
83 // XEnumerationAccess
86 {
88 }
89 uno::Reference< container::XEnumeration >
91 {
92  // #FIXME it's possible the WorkBookEnumImpl here doesn't reflect
93  // the state of this object ( although it should ) would be
94  // safer to create an enumeration based on this objects state
95  // rather than one effectively based of the desktop component
96  uno::Reference< container::XEnumerationAccess > xEnumerationAccess( m_xIndexAccess, uno::UNO_QUERY_THROW );
97  return new WorkBookEnumImpl( mxParent, mxContext, xEnumerationAccess->createEnumeration() );
98 }
99 
100 uno::Any
101 ScVbaWorkbooks::createCollectionObject( const css::uno::Any& aSource )
102 {
103  uno::Reference< sheet::XSpreadsheetDocument > xDoc( aSource, uno::UNO_QUERY_THROW );
104  return getWorkbook( mxContext, xDoc, mxParent );
105 }
106 
107 uno::Any SAL_CALL
108 ScVbaWorkbooks::Add( const uno::Any& Template )
109 {
110  uno::Reference< sheet::XSpreadsheetDocument > xSpreadDoc;
111  sal_Int32 nWorkbookType = 0;
112  OUString aTemplateFileName;
113  if( Template >>= nWorkbookType )
114  {
115  // nWorkbookType is a constant from XlWBATemplate (added in Excel 2007)
116  // TODO: create chart-sheet if supported by Calc
117 
118  xSpreadDoc.set( createDocument(), uno::UNO_QUERY_THROW );
119  // create a document with one sheet only
120  uno::Reference< sheet::XSpreadsheets > xSheets( xSpreadDoc->getSheets(), uno::UNO_SET_THROW );
121  uno::Reference< container::XIndexAccess > xSheetsIA( xSheets, uno::UNO_QUERY_THROW );
122  while( xSheetsIA->getCount() > 1 )
123  {
124  uno::Reference< container::XNamed > xSheetName( xSheetsIA->getByIndex( xSheetsIA->getCount() - 1 ), uno::UNO_QUERY_THROW );
125  xSheets->removeByName( xSheetName->getName() );
126  }
127  }
128  else if( Template >>= aTemplateFileName )
129  {
130  // TODO: create document from template
131  xSpreadDoc.set( createDocument(), uno::UNO_QUERY_THROW );
132  }
133  else if( !Template.hasValue() )
134  {
135  // regular spreadsheet document with configured number of sheets
136  xSpreadDoc.set( createDocument(), uno::UNO_QUERY_THROW );
137  }
138  else
139  {
140  // illegal argument
141  throw uno::RuntimeException();
142  }
143 
144  // need to set up the document modules ( and vba mode ) here
145  excel::setUpDocumentModules( xSpreadDoc );
146  if( xSpreadDoc.is() )
147  return getWorkbook( mxContext, xSpreadDoc, mxParent );
148  return uno::Any();
149 }
150 
151 void SAL_CALL
153 {
154 }
155 
156 bool
157 ScVbaWorkbooks::isTextFile( std::u16string_view sType )
158 {
159  // will return true if the file is
160  // a) a variant of a text file
161  // b) a csv file
162  // c) unknown
163  // returning true basically means treat this like a csv file
164  return sType == u"generic_Text" || sType.empty();
165 }
166 
167 bool
168 ScVbaWorkbooks::isSpreadSheetFile( std::u16string_view sType )
169 {
170  // include calc_QPro etc. ? ( not for the moment anyway )
171  return o3tl::starts_with( sType, u"calc_MS" )
172  || o3tl::starts_with( sType, u"MS Excel" )
173  || o3tl::starts_with( sType, u"calc8" )
174  || o3tl::starts_with( sType, u"calc_StarOffice" );
175 }
176 
177 OUString
178 ScVbaWorkbooks::getFileFilterType( const OUString& rFileName )
179 {
180  uno::Reference< document::XTypeDetection > xTypeDetect( mxContext->getServiceManager()->createInstanceWithContext("com.sun.star.document.TypeDetection", mxContext), uno::UNO_QUERY_THROW );
181  uno::Sequence< beans::PropertyValue > aMediaDesc(1);
182  aMediaDesc[ 0 ].Name = "URL";
183  aMediaDesc[ 0 ].Value <<= rFileName;
184  OUString sType = xTypeDetect->queryTypeByDescriptor( aMediaDesc, true );
185  return sType;
186 }
187 
188 // #TODO# #FIXME# can any of the unused params below be used?
189 uno::Any SAL_CALL
190 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*/ )
191 {
192  // we need to detect if this is a URL, if not then assume it's a file path
193  OUString aURL;
194  INetURLObject aObj;
195  aObj.SetURL( rFileName );
196  bool bIsURL = aObj.GetProtocol() != INetProtocol::NotValid;
197  if ( bIsURL )
198  aURL = rFileName;
199  else
200  osl::FileBase::getFileURLFromSystemPath( rFileName, aURL );
201 
202  uno::Sequence< beans::PropertyValue > sProps(0);
203 
204  OUString sType = getFileFilterType( aURL );
205  // A text file means it needs to be processed as a csv file
206  if ( isTextFile( sType ) )
207  {
208  sal_Int32 nIndex = 0;
209  // Values for format
210  // 1 Tabs
211  // 2 Commas
212  // 3 Spaces
213  // 4 Semicolons
214  // 5 Nothing
215  // 6 Custom character (see the Delimiter argument
216  // no format means use the current delimiter
217  sProps.realloc( 3 );
218  sProps[ nIndex ].Name = "FilterOptions";
219  sal_Int16 const delims[] { 0 /*default not used*/, 9/*tab*/, 44/*comma*/, 32/*space*/, 59/*semicolon*/ };
220 
221  OUString sFormat;
222  sal_Int16 nFormat = 0; // default indicator
223 
224  if ( Format.hasValue() )
225  {
226  Format >>= nFormat; // val of nFormat overwritten if extracted
227  // validate param
228  if ( nFormat < 1 || nFormat > 6 )
229  throw uno::RuntimeException("Illegal value for Format" );
230  }
231 
232  sal_Int16 nDelim = getCurrentDelim();
233 
234  if ( nFormat > 0 && nFormat < CUSTOM_CHAR )
235  {
236  nDelim = delims[ nFormat ];
237  }
238  else if ( nFormat > CUSTOM_CHAR )
239  {
240  // Need to check Delimiter param
241  if ( !Delimiter.hasValue() )
242  throw uno::RuntimeException("Expected value for Delimiter" );
243  OUString sStr;
244  Delimiter >>= sStr;
245  if ( sStr.isEmpty() )
246  throw uno::RuntimeException("Incorrect value for Delimiter" );
247 
248  nDelim = sStr[0];
249 
250  }
251 
252  getCurrentDelim() = nDelim; //set new current
253 
254  sFormat = OUString::number( nDelim ) + ",34,0,1";
255  sProps[ nIndex++ ].Value <<= sFormat;
256  sProps[ nIndex ].Name = "FilterName";
257  sProps[ nIndex++ ].Value <<= OUString( SC_TEXT_CSV_FILTER_NAME );
258  // Ensure WORKAROUND_CSV_TXT_BUG_i60158 gets called in typedetection.cxx so
259  // csv is forced for deep detected 'writerxxx' types
260  sProps[ nIndex ].Name = "DocumentService";
261  sProps[ nIndex ].Value <<= OUString("com.sun.star.sheet.SpreadsheetDocument");
262  }
263  else if ( !isSpreadSheetFile( sType ) )
264  throw uno::RuntimeException("Bad Format" );
265 
266  uno::Reference <sheet::XSpreadsheetDocument> xSpreadDoc( openDocument( rFileName, ReadOnly, sProps ), uno::UNO_QUERY_THROW );
267  uno::Any aRet = getWorkbook( mxContext, xSpreadDoc, mxParent );
268  uno::Reference< excel::XWorkbook > xWBook( aRet, uno::UNO_QUERY );
269  if ( xWBook.is() )
270  xWBook->Activate();
271  return aRet;
272 }
273 
274 OUString
276 {
277  return "ScVbaWorkbooks";
278 }
279 
280 css::uno::Sequence<OUString>
282 {
283  static uno::Sequence< OUString > const sNames
284  {
285  "ooo.vba.excel.Workbooks"
286  };
287  return sNames;
288 }
289 
290 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
virtual css::uno::Reference< css::container::XEnumeration > SAL_CALL createEnumeration() override
ScVbaWorkbooks(const css::uno::Reference< ov::XHelperInterface > &xParent, const css::uno::Reference< css::uno::XComponentContext > &xContext)
URL aURL
bool hasValue()
sal_Int32 nIndex
void setUpDocumentModules(const uno::Reference< sheet::XSpreadsheetDocument > &xDoc)
uno::Reference< uno::XComponentContext > mxContext
WeakReference< XInterface > mxParent
virtual css::uno::Sequence< OUString > getServiceNames() override
const sal_Int16 CUSTOM_CHAR
constexpr bool starts_with(std::basic_string_view< charT, traits > sv, std::basic_string_view< charT, traits > x) noexcept
virtual OUString getServiceImplName() override
static sal_Int16 & getCurrentDelim()
virtual void SAL_CALL Close() override
virtual css::uno::Type SAL_CALL getElementType() override
virtual css::uno::Any SAL_CALL Add(const css::uno::Any &Template) override
OptionalString sType
float u
virtual css::uno::Any createCollectionObject(const css::uno::Any &aSource) override
css::uno::Type const & get()
static uno::Any getWorkbook(const uno::Reference< uno::XComponentContext > &xContext, const uno::Reference< sheet::XSpreadsheetDocument > &xDoc, const uno::Reference< XHelperInterface > &xParent)
virtual css::uno::Any SAL_CALL Open(const OUString &Filename, const css::uno::Any &UpdateLinks, const css::uno::Any &ReadOnly, const css::uno::Any &Format, const css::uno::Any &Password, const css::uno::Any &WriteResPassword, const css::uno::Any &IgnoreReadOnlyRecommended, const css::uno::Any &Origin, const css::uno::Any &Delimiter, const css::uno::Any &Editable, const css::uno::Any &Notify, const css::uno::Any &Converter, const css::uno::Any &AddToMru) override
uno::Reference< XHelperInterface > getVBADocument(const uno::Reference< frame::XModel > &xModel)
INetProtocol GetProtocol() const
#define SC_TEXT_CSV_FILTER_NAME
Definition: global.hxx:61
OUString getFileFilterType(const OUString &rString)
bool SetURL(OUString const &rTheAbsURIRef, EncodeMechanism eMechanism=EncodeMechanism::WasEncoded, rtl_TextEncoding eCharset=RTL_TEXTENCODING_UTF8)
Reference< XModel > xModel
static bool isSpreadSheetFile(std::u16string_view rString)
cppu::ImplInheritanceHelper< VbaDocumentsBase, ov::excel::XWorkbooks > ScVbaWorkbooks_BASE
static bool isTextFile(std::u16string_view rString)