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