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 <com/sun/star/container/XNameContainer.hpp>
22 #include <com/sun/star/script/ModuleInfo.hpp>
23 #include <com/sun/star/script/ModuleType.hpp>
24 #include <com/sun/star/script/vba/XVBAModuleInfo.hpp>
25 #include <com/sun/star/awt/KeyEvent.hpp>
26 #include <osl/diagnose.h>
27 #include <rtl/character.hxx>
28 #include <o3tl/string_view.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 using namespace ::com::sun::star::script::vba
;
40 using namespace ::com::sun::star::uno
;
41 using namespace ::com::sun::star
;
43 using ::com::sun::star::awt::KeyEvent
;
45 VbaModule::VbaModule( const Reference
< XComponentContext
>& rxContext
,
46 const Reference
< frame::XModel
>& rxDocModel
,
47 OUString aName
, rtl_TextEncoding eTextEnc
, bool bExecutable
) :
48 mxContext( rxContext
),
49 mxDocModel( rxDocModel
),
50 maName(std::move( aName
)),
51 meTextEnc( eTextEnc
),
52 mnType( script::ModuleType::UNKNOWN
),
53 mnOffset( SAL_MAX_UINT32
),
56 mbExecutable( bExecutable
)
60 void VbaModule::importDirRecords( BinaryInputStream
& rDirStrm
)
62 sal_uInt16 nRecId
= 0;
63 StreamDataSequence aRecData
;
64 while( VbaHelper::readDirRecord( nRecId
, aRecData
, rDirStrm
) && (nRecId
!= VBA_ID_MODULEEND
) )
66 SequenceInputStream
aRecStrm( aRecData
);
67 sal_Int32 nRecSize
= aRecData
.getLength();
70 #define OOX_ENSURE_RECORDSIZE( cond ) OSL_ENSURE( cond, "VbaModule::importDirRecords - invalid record size" )
71 case VBA_ID_MODULENAME
:
72 OSL_FAIL( "VbaModule::importDirRecords - unexpected MODULENAME record" );
73 maName
= aRecStrm
.readCharArrayUC( nRecSize
, meTextEnc
);
75 case VBA_ID_MODULENAMEUNICODE
:
77 case VBA_ID_MODULESTREAMNAME
:
78 maStreamName
= aRecStrm
.readCharArrayUC( nRecSize
, meTextEnc
);
79 // Actually the stream name seems the best name to use
80 // the VBA_ID_MODULENAME name can sometimes be the wrong case
81 maName
= maStreamName
;
83 case VBA_ID_MODULESTREAMNAMEUNICODE
:
85 case VBA_ID_MODULEDOCSTRING
:
86 maDocString
= aRecStrm
.readCharArrayUC( nRecSize
, meTextEnc
);
88 case VBA_ID_MODULEDOCSTRINGUNICODE
:
90 case VBA_ID_MODULEOFFSET
:
91 OOX_ENSURE_RECORDSIZE( nRecSize
== 4 );
92 mnOffset
= aRecStrm
.readuInt32();
94 case VBA_ID_MODULEHELPCONTEXT
:
95 OOX_ENSURE_RECORDSIZE( nRecSize
== 4 );
97 case VBA_ID_MODULECOOKIE
:
98 OOX_ENSURE_RECORDSIZE( nRecSize
== 2 );
100 case VBA_ID_MODULETYPEPROCEDURAL
:
101 OOX_ENSURE_RECORDSIZE( nRecSize
== 0 );
102 OSL_ENSURE( mnType
== script::ModuleType::UNKNOWN
, "VbaModule::importDirRecords - multiple module type records" );
103 mnType
= script::ModuleType::NORMAL
;
105 case VBA_ID_MODULETYPEDOCUMENT
:
106 OOX_ENSURE_RECORDSIZE( nRecSize
== 0 );
107 OSL_ENSURE( mnType
== script::ModuleType::UNKNOWN
, "VbaModule::importDirRecords - multiple module type records" );
108 mnType
= script::ModuleType::DOCUMENT
;
110 case VBA_ID_MODULEREADONLY
:
111 OOX_ENSURE_RECORDSIZE( nRecSize
== 0 );
114 case VBA_ID_MODULEPRIVATE
:
115 OOX_ENSURE_RECORDSIZE( nRecSize
== 0 );
119 OSL_FAIL( "VbaModule::importDirRecords - unknown module record" );
120 #undef OOX_ENSURE_RECORDSIZE
123 OSL_ENSURE( !maName
.isEmpty(), "VbaModule::importDirRecords - missing module name" );
124 OSL_ENSURE( !maStreamName
.isEmpty(), "VbaModule::importDirRecords - missing module stream name" );
125 OSL_ENSURE( mnType
!= script::ModuleType::UNKNOWN
, "VbaModule::importDirRecords - missing module type" );
126 OSL_ENSURE( mnOffset
< SAL_MAX_UINT32
, "VbaModule::importDirRecords - missing module stream offset" );
129 void VbaModule::createAndImportModule( StorageBase
& rVbaStrg
,
130 const Reference
< container::XNameContainer
>& rxBasicLib
,
131 const Reference
< container::XNameAccess
>& rxDocObjectNA
)
133 OUString aVBASourceCode
= readSourceCode( rVbaStrg
);
134 createModule( aVBASourceCode
, rxBasicLib
, rxDocObjectNA
);
135 registerShortcutKeys();
138 void VbaModule::registerShortcutKeys()
140 for (VbaMacroKeyAndMethodBinding
const& rKeyBinding
: maKeyBindings
)
144 KeyEvent aKeyEvent
= ooo::vba::parseKeyEvent(rKeyBinding
.msApiKey
);
145 ooo::vba::applyShortCutKeyBinding(mxDocModel
, aKeyEvent
, rKeyBinding
.msMethodName
);
147 catch (const Exception
&)
153 void VbaModule::createEmptyModule( const Reference
< container::XNameContainer
>& rxBasicLib
,
154 const Reference
< container::XNameAccess
>& rxDocObjectNA
) const
156 createModule( u
"", rxBasicLib
, rxDocObjectNA
);
159 OUString
VbaModule::readSourceCode( StorageBase
& rVbaStrg
)
161 OUStringBuffer
aSourceCode(512);
162 static const char sUnmatchedRemovedTag
[] = "Rem removed unmatched Sub/End: ";
163 if( !maStreamName
.isEmpty() && (mnOffset
!= SAL_MAX_UINT32
) )
165 BinaryXInputStream
aInStrm( rVbaStrg
.openInputStream( maStreamName
), true );
166 OSL_ENSURE( !aInStrm
.isEof(), "VbaModule::readSourceCode - cannot open module stream" );
167 // skip the 'performance cache' stored before the actual source code
168 aInStrm
.seek( mnOffset
);
169 // if stream is still valid, load the source code
170 if( !aInStrm
.isEof() )
172 // decompression starts at current stream position of aInStrm
173 VbaInputStream
aVbaStrm( aInStrm
);
174 // load the source code line-by-line, with some more processing
175 TextInputStream
aVbaTextStrm( mxContext
, aVbaStrm
, meTextEnc
);
181 ProcedurePair() : bInProcedure( false ), nPos( 0 ) {};
184 while( !aVbaTextStrm
.isEof() )
186 OUString aCodeLine
= aVbaTextStrm
.readLine();
187 if( aCodeLine
.match( "Attribute " ) )
190 int index
= aCodeLine
.indexOf( ".VB_ProcData.VB_Invoke_Func = " );
194 // 'Attribute Procedure.VB_ProcData.VB_Invoke_Func = "*\n14"'
195 // where 'Procedure' is the procedure name and '*' is the shortcut key
196 // note: his is only relevant for Excel, seems that
197 // word doesn't store the shortcut in the module
199 int nSpaceIndex
= aCodeLine
.indexOf(' ');
200 OUString sProc
= aCodeLine
.copy( nSpaceIndex
+ 1, index
- nSpaceIndex
- 1);
201 // for Excel short cut key seems limited to cntrl+'a-z, A-Z'
202 std::u16string_view sKey
= aCodeLine
.subView( aCodeLine
.lastIndexOf("= ") + 3, 1 );
203 // only alpha key valid for key shortcut, however the api will accept other keys
204 if ( rtl::isAsciiAlpha( sKey
[ 0 ] ) )
206 // cntrl modifier is explicit ( but could be cntrl+shift ), parseKeyEvent
207 // will handle and uppercase letter appropriately
208 OUString sApiKey
= OUString::Concat("^") + sKey
;
209 maKeyBindings
.push_back({sApiKey
, sProc
});
215 // Hack here to weed out any unmatched End Sub / Sub Foo statements.
216 // The behaviour of the vba ide practically guarantees the case and
217 // spacing of Sub statement(s). However, indentation can be arbitrary hence
219 OUString
trimLine( aCodeLine
.trim() );
220 if ( mbExecutable
&& (
221 trimLine
.match("Sub ") ||
222 trimLine
.match("Public Sub ") ||
223 trimLine
.match("Private Sub ") ||
224 trimLine
.match("Static Sub ") ) )
226 // this should never happen, basic doesn't support nested procedures
227 // first Sub Foo must be bogus
228 if ( procInfo
.bInProcedure
)
230 // comment out the line
231 aSourceCode
.insert( procInfo
.nPos
, sUnmatchedRemovedTag
);
232 // mark location of this Sub
233 procInfo
.nPos
= aSourceCode
.getLength();
237 procInfo
.bInProcedure
= true;
238 procInfo
.nPos
= aSourceCode
.getLength();
241 else if ( mbExecutable
&& o3tl::starts_with(o3tl::trim(aCodeLine
), u
"End Sub") )
243 // un-matched End Sub
244 if ( !procInfo
.bInProcedure
)
246 aSourceCode
.append( sUnmatchedRemovedTag
);
250 procInfo
.bInProcedure
= false;
254 // normal source code line
256 aSourceCode
.append( "Rem " );
257 aSourceCode
.append( aCodeLine
+ "\n" );
262 return aSourceCode
.makeStringAndClear();
265 void VbaModule::createModule( std::u16string_view rVBASourceCode
,
266 const Reference
< container::XNameContainer
>& rxBasicLib
,
267 const Reference
< container::XNameAccess
>& rxDocObjectNA
) const
269 if( maName
.isEmpty() )
272 // prepare the Basic module
273 script::ModuleInfo aModuleInfo
;
274 aModuleInfo
.ModuleType
= mnType
;
275 OUStringBuffer
aSourceCode(512);
276 aSourceCode
.append( "Rem Attribute VBA_ModuleType=" );
279 case script::ModuleType::NORMAL
:
280 aSourceCode
.append( "VBAModule" );
282 case script::ModuleType::CLASS
:
283 aSourceCode
.append( "VBAClassModule" );
285 case script::ModuleType::FORM
:
286 aSourceCode
.append( "VBAFormModule" );
287 // hack from old filter, document Basic should know the XModel, but it doesn't
288 aModuleInfo
.ModuleObject
.set( mxDocModel
, UNO_QUERY
);
290 case script::ModuleType::DOCUMENT
:
291 aSourceCode
.append( "VBADocumentModule" );
292 // get the VBA implementation object associated to the document module
293 if( rxDocObjectNA
.is() ) try
295 aModuleInfo
.ModuleObject
.set( rxDocObjectNA
->getByName( maName
), UNO_QUERY
);
297 catch (const Exception
&)
302 aSourceCode
.append( "VBAUnknown" );
304 aSourceCode
.append( '\n' );
307 aSourceCode
.append( "Option VBASupport 1\n" );
308 if( mnType
== script::ModuleType::CLASS
)
309 aSourceCode
.append( "Option ClassModule\n" );
313 // add a subroutine named after the module itself
314 aSourceCode
.append( "Sub " + maName
.replace( ' ', '_' ) + "\n" );
317 // append passed VBA source code
318 aSourceCode
.append( rVBASourceCode
);
320 // close the subroutine named after the module
322 aSourceCode
.append( "End Sub\n" );
324 // insert extended module info
327 Reference
< XVBAModuleInfo
> xVBAModuleInfo( rxBasicLib
, UNO_QUERY_THROW
);
328 xVBAModuleInfo
->insertModuleInfo( maName
, aModuleInfo
);
330 catch (const Exception
&)
334 // insert the module into the passed Basic library
337 rxBasicLib
->insertByName( maName
, Any( aSourceCode
.makeStringAndClear() ) );
339 catch (const Exception
&)
341 OSL_FAIL( "VbaModule::createModule - cannot insert module into library" );
345 } // namespace oox::ole
347 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */