1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
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 .
20 #include "oox/ole/vbamodule.hxx"
21 #include <boost/unordered_map.hpp>
22 #include <com/sun/star/container/XNameContainer.hpp>
23 #include <com/sun/star/container/XIndexContainer.hpp>
24 #include <com/sun/star/script/ModuleInfo.hpp>
25 #include <com/sun/star/script/ModuleType.hpp>
26 #include <com/sun/star/script/vba/XVBAModuleInfo.hpp>
27 #include <com/sun/star/awt/KeyEvent.hpp>
28 #include <cppuhelper/implbase1.hxx>
29 #include <filter/msfilter/msvbahelper.hxx>
30 #include "oox/helper/binaryinputstream.hxx"
31 #include "oox/helper/storagebase.hxx"
32 #include "oox/helper/textinputstream.hxx"
33 #include "oox/ole/vbahelper.hxx"
34 #include "oox/ole/vbainputstream.hxx"
39 // ============================================================================
41 using namespace ::com::sun::star::lang
;
42 using namespace ::com::sun::star::script::vba
;
43 using namespace ::com::sun::star::uno
;
44 using namespace ::com::sun::star
;
46 using ::com::sun::star::awt::KeyEvent
;
47 // ============================================================================
48 typedef ::cppu::WeakImplHelper1
< container::XIndexContainer
> OleIdToNameContainer_BASE
;
49 typedef boost::unordered_map
< sal_Int32
, OUString
> ObjIdToName
;
51 class OleIdToNameContainer
: public OleIdToNameContainer_BASE
53 ObjIdToName ObjIdToNameHash
;
54 ::osl::Mutex m_aMutex
;
55 bool hasByIndex( ::sal_Int32 Index
)
57 ::osl::MutexGuard
aGuard( m_aMutex
);
58 return ( ObjIdToNameHash
.find( Index
) != ObjIdToNameHash
.end() );
61 OleIdToNameContainer() {}
62 // XIndexContainer Methods
63 virtual void SAL_CALL
insertByIndex( ::sal_Int32 Index
, const Any
& Element
) throw (IllegalArgumentException
, IndexOutOfBoundsException
, WrappedTargetException
, RuntimeException
)
65 ::osl::MutexGuard
aGuard( m_aMutex
);
67 if ( !( Element
>>= sOleName
) )
68 throw IllegalArgumentException();
69 ObjIdToNameHash
[ Index
] = sOleName
;
71 virtual void SAL_CALL
removeByIndex( ::sal_Int32 Index
) throw (IndexOutOfBoundsException
, WrappedTargetException
, RuntimeException
)
73 ::osl::MutexGuard
aGuard( m_aMutex
);
74 if ( !hasByIndex( Index
) )
75 throw IndexOutOfBoundsException();
76 ObjIdToNameHash
.erase( ObjIdToNameHash
.find( Index
) );
78 // XIndexReplace Methods
79 virtual void SAL_CALL
replaceByIndex( ::sal_Int32 Index
, const Any
& Element
) throw (IllegalArgumentException
, IndexOutOfBoundsException
, WrappedTargetException
, RuntimeException
)
81 ::osl::MutexGuard
aGuard( m_aMutex
);
82 if ( !hasByIndex( Index
) )
83 throw IndexOutOfBoundsException();
85 if ( !( Element
>>= sOleName
) )
86 throw IllegalArgumentException();
87 ObjIdToNameHash
[ Index
] = sOleName
;
89 // XIndexAccess Methods
90 virtual ::sal_Int32 SAL_CALL
getCount( ) throw (RuntimeException
)
92 ::osl::MutexGuard
aGuard( m_aMutex
);
93 return ObjIdToNameHash
.size();
95 virtual Any SAL_CALL
getByIndex( ::sal_Int32 Index
) throw (IndexOutOfBoundsException
, WrappedTargetException
, RuntimeException
)
97 ::osl::MutexGuard
aGuard( m_aMutex
);
98 if ( !hasByIndex( Index
) )
99 throw IndexOutOfBoundsException();
100 return makeAny( ObjIdToNameHash
[ Index
] );
102 // XElementAccess Methods
103 virtual Type SAL_CALL
getElementType( ) throw (RuntimeException
)
105 return ::getCppuType( static_cast< const OUString
* >( 0 ) );
107 virtual ::sal_Bool SAL_CALL
hasElements( ) throw (RuntimeException
)
109 ::osl::MutexGuard
aGuard( m_aMutex
);
110 return ( getCount() > 0 );
114 // ============================================================================
116 VbaModule::VbaModule( const Reference
< XComponentContext
>& rxContext
,
117 const Reference
< frame::XModel
>& rxDocModel
,
118 const OUString
& rName
, rtl_TextEncoding eTextEnc
, bool bExecutable
) :
119 mxContext( rxContext
),
120 mxDocModel( rxDocModel
),
122 meTextEnc( eTextEnc
),
123 mnType( script::ModuleType::UNKNOWN
),
124 mnOffset( SAL_MAX_UINT32
),
127 mbExecutable( bExecutable
)
131 void VbaModule::importDirRecords( BinaryInputStream
& rDirStrm
)
133 sal_uInt16 nRecId
= 0;
134 StreamDataSequence aRecData
;
135 while( VbaHelper::readDirRecord( nRecId
, aRecData
, rDirStrm
) && (nRecId
!= VBA_ID_MODULEEND
) )
137 SequenceInputStream
aRecStrm( aRecData
);
138 sal_Int32 nRecSize
= aRecData
.getLength();
141 #define OOX_ENSURE_RECORDSIZE( cond ) OSL_ENSURE( cond, "VbaModule::importDirRecords - invalid record size" )
142 case VBA_ID_MODULENAME
:
143 OSL_FAIL( "VbaModule::importDirRecords - unexpected MODULENAME record" );
144 maName
= aRecStrm
.readCharArrayUC( nRecSize
, meTextEnc
);
146 case VBA_ID_MODULENAMEUNICODE
:
148 case VBA_ID_MODULESTREAMNAME
:
149 maStreamName
= aRecStrm
.readCharArrayUC( nRecSize
, meTextEnc
);
150 // Actually the stream name seems the best name to use
151 // the VBA_ID_MODULENAME name can sometimes be the wrong case
152 maName
= maStreamName
;
154 case VBA_ID_MODULESTREAMNAMEUNICODE
:
156 case VBA_ID_MODULEDOCSTRING
:
157 maDocString
= aRecStrm
.readCharArrayUC( nRecSize
, meTextEnc
);
159 case VBA_ID_MODULEDOCSTRINGUNICODE
:
161 case VBA_ID_MODULEOFFSET
:
162 OOX_ENSURE_RECORDSIZE( nRecSize
== 4 );
163 aRecStrm
>> mnOffset
;
165 case VBA_ID_MODULEHELPCONTEXT
:
166 OOX_ENSURE_RECORDSIZE( nRecSize
== 4 );
168 case VBA_ID_MODULECOOKIE
:
169 OOX_ENSURE_RECORDSIZE( nRecSize
== 2 );
171 case VBA_ID_MODULETYPEPROCEDURAL
:
172 OOX_ENSURE_RECORDSIZE( nRecSize
== 0 );
173 OSL_ENSURE( mnType
== script::ModuleType::UNKNOWN
, "VbaModule::importDirRecords - multiple module type records" );
174 mnType
= script::ModuleType::NORMAL
;
176 case VBA_ID_MODULETYPEDOCUMENT
:
177 OOX_ENSURE_RECORDSIZE( nRecSize
== 0 );
178 OSL_ENSURE( mnType
== script::ModuleType::UNKNOWN
, "VbaModule::importDirRecords - multiple module type records" );
179 mnType
= script::ModuleType::DOCUMENT
;
181 case VBA_ID_MODULEREADONLY
:
182 OOX_ENSURE_RECORDSIZE( nRecSize
== 0 );
185 case VBA_ID_MODULEPRIVATE
:
186 OOX_ENSURE_RECORDSIZE( nRecSize
== 0 );
190 OSL_FAIL( "VbaModule::importDirRecords - unknown module record" );
191 #undef OOX_ENSURE_RECORDSIZE
194 OSL_ENSURE( !maName
.isEmpty(), "VbaModule::importDirRecords - missing module name" );
195 OSL_ENSURE( !maStreamName
.isEmpty(), "VbaModule::importDirRecords - missing module stream name" );
196 OSL_ENSURE( mnType
!= script::ModuleType::UNKNOWN
, "VbaModule::importDirRecords - missing module type" );
197 OSL_ENSURE( mnOffset
< SAL_MAX_UINT32
, "VbaModule::importDirRecords - missing module stream offset" );
200 void VbaModule::createAndImportModule( StorageBase
& rVbaStrg
,
201 const Reference
< container::XNameContainer
>& rxBasicLib
,
202 const Reference
< container::XNameAccess
>& rxDocObjectNA
) const
204 OUString aVBASourceCode
= readSourceCode( rVbaStrg
);
205 createModule( aVBASourceCode
, rxBasicLib
, rxDocObjectNA
);
208 void VbaModule::createEmptyModule( const Reference
< container::XNameContainer
>& rxBasicLib
,
209 const Reference
< container::XNameAccess
>& rxDocObjectNA
) const
211 createModule( OUString(), rxBasicLib
, rxDocObjectNA
);
214 OUString
VbaModule::readSourceCode( StorageBase
& rVbaStrg
) const
216 OUStringBuffer aSourceCode
;
217 const static OUString
sUnmatchedRemovedTag( "Rem removed unmatched Sub/End: " );
218 if( !maStreamName
.isEmpty() && (mnOffset
!= SAL_MAX_UINT32
) )
220 BinaryXInputStream
aInStrm( rVbaStrg
.openInputStream( maStreamName
), true );
221 OSL_ENSURE( !aInStrm
.isEof(), "VbaModule::readSourceCode - cannot open module stream" );
222 // skip the 'performance cache' stored before the actual source code
223 aInStrm
.seek( mnOffset
);
224 // if stream is still valid, load the source code
225 if( !aInStrm
.isEof() )
227 // decompression starts at current stream position of aInStrm
228 VbaInputStream
aVbaStrm( aInStrm
);
229 // load the source code line-by-line, with some more processing
230 TextInputStream
aVbaTextStrm( mxContext
, aVbaStrm
, meTextEnc
);
236 ProcedurePair() : bInProcedure( false ), nPos( 0 ) {};
239 while( !aVbaTextStrm
.isEof() )
241 OUString aCodeLine
= aVbaTextStrm
.readLine();
242 if( aCodeLine
.match( "Attribute " ) )
245 int index
= aCodeLine
.indexOf( ".VB_ProcData.VB_Invoke_Func = " );
249 // 'Attribute Procedure.VB_ProcData.VB_Invoke_Func = "*\n14"'
250 // where 'Procedure' is the procedure name and '*' is the shortcut key
251 // note: his is only relevant for Excel, seems that
252 // word doesn't store the shortcut in the module
254 int nSpaceIndex
= aCodeLine
.indexOf(' ');
255 OUString sProc
= aCodeLine
.copy( nSpaceIndex
+ 1, index
- nSpaceIndex
- 1);
256 // for Excel short cut key seems limited to cntrl+'a-z, A-Z'
257 OUString sKey
= aCodeLine
.copy( aCodeLine
.lastIndexOf("= ") + 3, 1 );
258 // only alpha key valid for key shortcut, however the api will accept other keys
259 if ( !isalpha( (char)sKey
[ 0 ] ) )
261 // cntrl modifier is explicit ( but could be cntrl+shift ), parseKeyEvent
262 // will handle and uppercase letter appropriately
263 OUString sApiKey
= "^";
267 KeyEvent aKeyEvent
= ooo::vba::parseKeyEvent( sApiKey
);
268 ooo::vba::applyShortCutKeyBinding( mxDocModel
, aKeyEvent
, sProc
);
270 catch (const Exception
&)
278 // Hack here to weed out any unmatched End Sub / Sub Foo statements.
279 // The behaviour of the vba ide practically guarantees the case and
280 // spacing of Sub statement(s). However, indentation can be arbitrary hence
282 OUString
trimLine( aCodeLine
.trim() );
283 if ( mbExecutable
&& (
284 trimLine
.match("Sub ") ||
285 trimLine
.match("Public Sub ") ||
286 trimLine
.match("Private Sub ") ||
287 trimLine
.match("Static Sub ") ) )
289 // this should never happen, basic doesn't support nested procedures
290 // first Sub Foo must be bogus
291 if ( procInfo
.bInProcedure
)
293 // comment out the line
294 aSourceCode
.insert( procInfo
.nPos
, sUnmatchedRemovedTag
);
295 // mark location of this Sub
296 procInfo
.nPos
= aSourceCode
.getLength();
300 procInfo
.bInProcedure
= true;
301 procInfo
.nPos
= aSourceCode
.getLength();
304 else if ( mbExecutable
&& aCodeLine
.trim().match("End Sub") )
306 // un-matched End Sub
307 if ( !procInfo
.bInProcedure
)
309 aSourceCode
.append( sUnmatchedRemovedTag
);
313 procInfo
.bInProcedure
= false;
317 // normal source code line
319 aSourceCode
.appendAscii( "Rem " );
320 aSourceCode
.append( aCodeLine
).append( '\n' );
325 return aSourceCode
.makeStringAndClear();
328 void VbaModule::createModule( const OUString
& rVBASourceCode
,
329 const Reference
< container::XNameContainer
>& rxBasicLib
,
330 const Reference
< container::XNameAccess
>& rxDocObjectNA
) const
332 if( maName
.isEmpty() )
335 // prepare the Basic module
336 script::ModuleInfo aModuleInfo
;
337 aModuleInfo
.ModuleType
= mnType
;
338 OUStringBuffer aSourceCode
;
339 aSourceCode
.appendAscii( "Rem Attribute VBA_ModuleType=" );
342 case script::ModuleType::NORMAL
:
343 aSourceCode
.appendAscii( "VBAModule" );
345 case script::ModuleType::CLASS
:
346 aSourceCode
.appendAscii( "VBAClassModule" );
348 case script::ModuleType::FORM
:
349 aSourceCode
.appendAscii( "VBAFormModule" );
350 // hack from old filter, document Basic should know the XModel, but it doesn't
351 aModuleInfo
.ModuleObject
.set( mxDocModel
, UNO_QUERY
);
353 case script::ModuleType::DOCUMENT
:
354 aSourceCode
.appendAscii( "VBADocumentModule" );
355 // get the VBA implementation object associated to the document module
356 if( rxDocObjectNA
.is() ) try
358 aModuleInfo
.ModuleObject
.set( rxDocObjectNA
->getByName( maName
), UNO_QUERY
);
360 catch (const Exception
&)
365 aSourceCode
.appendAscii( "VBAUnknown" );
367 aSourceCode
.append( '\n' );
370 aSourceCode
.appendAscii( "Option VBASupport 1\n" );
371 if( mnType
== script::ModuleType::CLASS
)
372 aSourceCode
.appendAscii( "Option ClassModule\n" );
376 // add a subroutine named after the module itself
377 aSourceCode
.appendAscii( "Sub " ).
378 append( maName
.replace( ' ', '_' ) ).append( '\n' );
381 // append passed VBA source code
382 aSourceCode
.append( rVBASourceCode
);
384 // close the subroutine named after the module
386 aSourceCode
.appendAscii( "End Sub\n" );
388 // insert extended module info
391 Reference
< XVBAModuleInfo
> xVBAModuleInfo( rxBasicLib
, UNO_QUERY_THROW
);
392 xVBAModuleInfo
->insertModuleInfo( maName
, aModuleInfo
);
394 catch (const Exception
&)
398 // insert the module into the passed Basic library
401 rxBasicLib
->insertByName( maName
, Any( aSourceCode
.makeStringAndClear() ) );
403 catch (const Exception
&)
405 OSL_FAIL( "VbaModule::createModule - cannot insert module into library" );
409 // ============================================================================
414 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */