LibreOffice Module oox (master) 1
vbamodule.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 <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>
33#include <oox/ole/vbahelper.hxx>
35#include <utility>
36
37namespace oox::ole {
38
39using namespace ::com::sun::star::lang;
40using namespace ::com::sun::star::script::vba;
41using namespace ::com::sun::star::uno;
42using namespace ::com::sun::star;
43
44using ::com::sun::star::awt::KeyEvent;
45
46VbaModule::VbaModule( const Reference< XComponentContext >& rxContext,
47 const Reference< frame::XModel >& rxDocModel,
48 OUString aName, rtl_TextEncoding eTextEnc, bool bExecutable ) :
49 mxContext( rxContext ),
50 mxDocModel( rxDocModel ),
51 maName(std::move( aName )),
52 meTextEnc( eTextEnc ),
53 mnType( script::ModuleType::UNKNOWN ),
54 mnOffset( SAL_MAX_UINT32 ),
55 mbReadOnly( false ),
56 mbPrivate( false ),
57 mbExecutable( bExecutable )
58{
59}
60
62{
63 sal_uInt16 nRecId = 0;
64 StreamDataSequence aRecData;
65 while( VbaHelper::readDirRecord( nRecId, aRecData, rDirStrm ) && (nRecId != VBA_ID_MODULEEND) )
66 {
67 SequenceInputStream aRecStrm( aRecData );
68 sal_Int32 nRecSize = aRecData.getLength();
69 switch( nRecId )
70 {
71#define OOX_ENSURE_RECORDSIZE( cond ) OSL_ENSURE( cond, "VbaModule::importDirRecords - invalid record size" )
73 OSL_FAIL( "VbaModule::importDirRecords - unexpected MODULENAME record" );
74 maName = aRecStrm.readCharArrayUC( nRecSize, meTextEnc );
75 break;
77 break;
79 maStreamName = aRecStrm.readCharArrayUC( nRecSize, meTextEnc );
80 // Actually the stream name seems the best name to use
81 // the VBA_ID_MODULENAME name can sometimes be the wrong case
83 break;
85 break;
87 maDocString = aRecStrm.readCharArrayUC( nRecSize, meTextEnc );
88 break;
90 break;
92 OOX_ENSURE_RECORDSIZE( nRecSize == 4 );
93 mnOffset = aRecStrm.readuInt32();
94 break;
96 OOX_ENSURE_RECORDSIZE( nRecSize == 4 );
97 break;
99 OOX_ENSURE_RECORDSIZE( nRecSize == 2 );
100 break;
102 OOX_ENSURE_RECORDSIZE( nRecSize == 0 );
103 OSL_ENSURE( mnType == script::ModuleType::UNKNOWN, "VbaModule::importDirRecords - multiple module type records" );
104 mnType = script::ModuleType::NORMAL;
105 break;
107 OOX_ENSURE_RECORDSIZE( nRecSize == 0 );
108 OSL_ENSURE( mnType == script::ModuleType::UNKNOWN, "VbaModule::importDirRecords - multiple module type records" );
109 mnType = script::ModuleType::DOCUMENT;
110 break;
112 OOX_ENSURE_RECORDSIZE( nRecSize == 0 );
113 mbReadOnly = true;
114 break;
116 OOX_ENSURE_RECORDSIZE( nRecSize == 0 );
117 mbPrivate = true;
118 break;
119 default:
120 OSL_FAIL( "VbaModule::importDirRecords - unknown module record" );
121#undef OOX_ENSURE_RECORDSIZE
122 }
123 }
124 OSL_ENSURE( !maName.isEmpty(), "VbaModule::importDirRecords - missing module name" );
125 OSL_ENSURE( !maStreamName.isEmpty(), "VbaModule::importDirRecords - missing module stream name" );
126 OSL_ENSURE( mnType != script::ModuleType::UNKNOWN, "VbaModule::importDirRecords - missing module type" );
127 OSL_ENSURE( mnOffset < SAL_MAX_UINT32, "VbaModule::importDirRecords - missing module stream offset" );
128}
129
131 const Reference< container::XNameContainer >& rxBasicLib,
132 const Reference< container::XNameAccess >& rxDocObjectNA )
133{
134 OUString aVBASourceCode = readSourceCode( rVbaStrg );
135 createModule( aVBASourceCode, rxBasicLib, rxDocObjectNA );
137}
138
140{
141 for (VbaMacroKeyAndMethodBinding const& rKeyBinding : maKeyBindings)
142 {
143 try
144 {
145 KeyEvent aKeyEvent = ooo::vba::parseKeyEvent(rKeyBinding.msApiKey);
146 ooo::vba::applyShortCutKeyBinding(mxDocModel, aKeyEvent, rKeyBinding.msMethodName);
147 }
148 catch (const Exception&)
149 {
150 }
151 }
152}
153
154void VbaModule::createEmptyModule( const Reference< container::XNameContainer >& rxBasicLib,
155 const Reference< container::XNameAccess >& rxDocObjectNA ) const
156{
157 createModule( u"", rxBasicLib, rxDocObjectNA );
158}
159
161{
162 OUStringBuffer aSourceCode(512);
163 static const char sUnmatchedRemovedTag[] = "Rem removed unmatched Sub/End: ";
164 if( !maStreamName.isEmpty() && (mnOffset != SAL_MAX_UINT32) )
165 {
166 BinaryXInputStream aInStrm( rVbaStrg.openInputStream( maStreamName ), true );
167 OSL_ENSURE( !aInStrm.isEof(), "VbaModule::readSourceCode - cannot open module stream" );
168 // skip the 'performance cache' stored before the actual source code
169 aInStrm.seek( mnOffset );
170 // if stream is still valid, load the source code
171 if( !aInStrm.isEof() )
172 {
173 // decompression starts at current stream position of aInStrm
174 VbaInputStream aVbaStrm( aInStrm );
175 // load the source code line-by-line, with some more processing
176 TextInputStream aVbaTextStrm( mxContext, aVbaStrm, meTextEnc );
177
178 struct ProcedurePair
179 {
180 bool bInProcedure;
181 sal_uInt32 nPos;
182 ProcedurePair() : bInProcedure( false ), nPos( 0 ) {};
183 } procInfo;
184
185 while( !aVbaTextStrm.isEof() )
186 {
187 OUString aCodeLine = aVbaTextStrm.readLine();
188 if( aCodeLine.match( "Attribute " ) )
189 {
190 // attribute
191 int index = aCodeLine.indexOf( ".VB_ProcData.VB_Invoke_Func = " );
192 if ( index != -1 )
193 {
194 // format is
195 // 'Attribute Procedure.VB_ProcData.VB_Invoke_Func = "*\n14"'
196 // where 'Procedure' is the procedure name and '*' is the shortcut key
197 // note: his is only relevant for Excel, seems that
198 // word doesn't store the shortcut in the module
199 // attributes
200 int nSpaceIndex = aCodeLine.indexOf(' ');
201 OUString sProc = aCodeLine.copy( nSpaceIndex + 1, index - nSpaceIndex - 1);
202 // for Excel short cut key seems limited to cntrl+'a-z, A-Z'
203 std::u16string_view sKey = aCodeLine.subView( aCodeLine.lastIndexOf("= ") + 3, 1 );
204 // only alpha key valid for key shortcut, however the api will accept other keys
205 if ( rtl::isAsciiAlpha( sKey[ 0 ] ) )
206 {
207 // cntrl modifier is explicit ( but could be cntrl+shift ), parseKeyEvent
208 // will handle and uppercase letter appropriately
209 OUString sApiKey = OUString::Concat("^") + sKey;
210 maKeyBindings.push_back({sApiKey, sProc});
211 }
212 }
213 }
214 else
215 {
216 // Hack here to weed out any unmatched End Sub / Sub Foo statements.
217 // The behaviour of the vba ide practically guarantees the case and
218 // spacing of Sub statement(s). However, indentation can be arbitrary hence
219 // the trim.
220 OUString trimLine( aCodeLine.trim() );
221 if ( mbExecutable && (
222 trimLine.match("Sub ") ||
223 trimLine.match("Public Sub ") ||
224 trimLine.match("Private Sub ") ||
225 trimLine.match("Static Sub ") ) )
226 {
227 // this should never happen, basic doesn't support nested procedures
228 // first Sub Foo must be bogus
229 if ( procInfo.bInProcedure )
230 {
231 // comment out the line
232 aSourceCode.insert( procInfo.nPos, sUnmatchedRemovedTag );
233 // mark location of this Sub
234 procInfo.nPos = aSourceCode.getLength();
235 }
236 else
237 {
238 procInfo.bInProcedure = true;
239 procInfo.nPos = aSourceCode.getLength();
240 }
241 }
242 else if ( mbExecutable && o3tl::starts_with(o3tl::trim(aCodeLine), u"End Sub") )
243 {
244 // un-matched End Sub
245 if ( !procInfo.bInProcedure )
246 {
247 aSourceCode.append( sUnmatchedRemovedTag );
248 }
249 else
250 {
251 procInfo.bInProcedure = false;
252 procInfo.nPos = 0;
253 }
254 }
255 // normal source code line
256 if( !mbExecutable )
257 aSourceCode.append( "Rem " );
258 aSourceCode.append( aCodeLine ).append( '\n' );
259 }
260 }
261 }
262 }
263 return aSourceCode.makeStringAndClear();
264}
265
266void VbaModule::createModule( std::u16string_view rVBASourceCode,
267 const Reference< container::XNameContainer >& rxBasicLib,
268 const Reference< container::XNameAccess >& rxDocObjectNA ) const
269{
270 if( maName.isEmpty() )
271 return;
272
273 // prepare the Basic module
274 script::ModuleInfo aModuleInfo;
275 aModuleInfo.ModuleType = mnType;
276 OUStringBuffer aSourceCode(512);
277 aSourceCode.append( "Rem Attribute VBA_ModuleType=" );
278 switch( mnType )
279 {
280 case script::ModuleType::NORMAL:
281 aSourceCode.append( "VBAModule" );
282 break;
283 case script::ModuleType::CLASS:
284 aSourceCode.append( "VBAClassModule" );
285 break;
286 case script::ModuleType::FORM:
287 aSourceCode.append( "VBAFormModule" );
288 // hack from old filter, document Basic should know the XModel, but it doesn't
289 aModuleInfo.ModuleObject.set( mxDocModel, UNO_QUERY );
290 break;
291 case script::ModuleType::DOCUMENT:
292 aSourceCode.append( "VBADocumentModule" );
293 // get the VBA implementation object associated to the document module
294 if( rxDocObjectNA.is() ) try
295 {
296 aModuleInfo.ModuleObject.set( rxDocObjectNA->getByName( maName ), UNO_QUERY );
297 }
298 catch (const Exception&)
299 {
300 }
301 break;
302 default:
303 aSourceCode.append( "VBAUnknown" );
304 }
305 aSourceCode.append( '\n' );
306 if( mbExecutable )
307 {
308 aSourceCode.append( "Option VBASupport 1\n" );
309 if( mnType == script::ModuleType::CLASS )
310 aSourceCode.append( "Option ClassModule\n" );
311 }
312 else
313 {
314 // add a subroutine named after the module itself
315 aSourceCode.append( "Sub " + maName.replace( ' ', '_' ) + "\n" );
316 }
317
318 // append passed VBA source code
319 aSourceCode.append( rVBASourceCode );
320
321 // close the subroutine named after the module
322 if( !mbExecutable )
323 aSourceCode.append( "End Sub\n" );
324
325 // insert extended module info
326 try
327 {
328 Reference< XVBAModuleInfo > xVBAModuleInfo( rxBasicLib, UNO_QUERY_THROW );
329 xVBAModuleInfo->insertModuleInfo( maName, aModuleInfo );
330 }
331 catch (const Exception&)
332 {
333 }
334
335 // insert the module into the passed Basic library
336 try
337 {
338 rxBasicLib->insertByName( maName, Any( aSourceCode.makeStringAndClear() ) );
339 }
340 catch (const Exception&)
341 {
342 OSL_FAIL( "VbaModule::createModule - cannot insert module into library" );
343 }
344}
345
346} // namespace oox::ole
347
348/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
sal_Int16 script
Interface for binary input stream classes.
OUString readCharArrayUC(sal_Int32 nChars, rtl_TextEncoding eTextEnc)
Reads a byte character array and returns a Unicode string.
bool isEof() const
Returns true, if the stream position is invalid (EOF).
Wraps a UNO input stream and provides convenient access functions.
virtual void seek(sal_Int64 nPos) override
Seeks the stream to the passed position, if wrapped stream is seekable.
Wraps a StreamDataSequence and provides convenient access functions.
Base class for storage access implementations.
Definition: storagebase.hxx:52
css::uno::Reference< css::io::XInputStream > openInputStream(const OUString &rStreamName)
Opens and returns the specified input stream from the storage.
bool isEof() const
Returns true, if no more text is available in the stream.
OUString readLine()
Reads a text line from the stream.
A non-seekable input stream that implements run-length decompression.
css::uno::Reference< css::frame::XModel > mxDocModel
Document model used to import/export the VBA project.
Definition: vbamodule.hxx:103
void createAndImportModule(StorageBase &rVbaStrg, const css::uno::Reference< css::container::XNameContainer > &rxBasicLib, const css::uno::Reference< css::container::XNameAccess > &rxDocObjectNA)
Imports the VBA source code into the passed Basic library.
Definition: vbamodule.cxx:130
sal_uInt32 mnOffset
Definition: vbamodule.hxx:109
css::uno::Reference< css::uno::XComponentContext > mxContext
Component context with service manager.
Definition: vbamodule.hxx:101
rtl_TextEncoding meTextEnc
Definition: vbamodule.hxx:107
std::vector< VbaMacroKeyAndMethodBinding > maKeyBindings
Keys and VBA macro method bindings.
Definition: vbamodule.hxx:115
void registerShortcutKeys()
Definition: vbamodule.cxx:139
void createModule(std::u16string_view rVBASourceCode, const css::uno::Reference< css::container::XNameContainer > &rxBasicLib, const css::uno::Reference< css::container::XNameAccess > &rxDocObjectNA) const
Creates a new Basic module and inserts it into the passed Basic library.
Definition: vbamodule.cxx:266
void importDirRecords(BinaryInputStream &rDirStrm)
Imports all records for this module until the MODULEEND record.
Definition: vbamodule.cxx:61
VbaModule(const css::uno::Reference< css::uno::XComponentContext > &rxContext, const css::uno::Reference< css::frame::XModel > &rxDocModel, OUString aName, rtl_TextEncoding eTextEnc, bool bExecutable)
Definition: vbamodule.cxx:46
void createEmptyModule(const css::uno::Reference< css::container::XNameContainer > &rxBasicLib, const css::uno::Reference< css::container::XNameAccess > &rxDocObjectNA) const
Creates an empty Basic module in the passed Basic library.
Definition: vbamodule.cxx:154
OUString readSourceCode(StorageBase &rVbaStrg)
Reads and returns the VBA source code from the passed storage.
Definition: vbamodule.cxx:160
OUString maName
Definition: dffdumper.cxx:161
uno::Reference< uno::XComponentContext > mxContext
float u
UNKNOWN
OUString aName
sal_uInt16 nPos
@ Exception
index
constexpr bool starts_with(std::basic_string_view< charT, traits > sv, std::basic_string_view< charT, traits > x) noexcept
std::u16string_view trim(std::u16string_view str)
awt::KeyEvent parseKeyEvent(const OUString &Key)
void applyShortCutKeyBinding(const uno::Reference< frame::XModel > &rxModel, const awt::KeyEvent &rKeyEvent, const OUString &rMacroName)
bool readDirRecord(sal_uInt16 &rnRecId, StreamDataSequence &rRecData, BinaryInputStream &rInStrm)
Reads the next record from the VBA directory stream 'dir'.
Definition: vbahelper.cxx:29
const sal_uInt16 VBA_ID_MODULEDOCSTRINGUNICODE
Definition: vbahelper.hxx:35
const sal_uInt16 VBA_ID_MODULEHELPCONTEXT
Definition: vbahelper.hxx:37
const sal_uInt16 VBA_ID_MODULETYPEPROCEDURAL
Definition: vbahelper.hxx:46
const sal_uInt16 VBA_ID_MODULENAME
Definition: vbahelper.hxx:38
const sal_uInt16 VBA_ID_MODULEDOCSTRING
Definition: vbahelper.hxx:34
const sal_uInt16 VBA_ID_MODULESTREAMNAMEUNICODE
Definition: vbahelper.hxx:44
const sal_uInt16 VBA_ID_MODULETYPEDOCUMENT
Definition: vbahelper.hxx:45
const sal_uInt16 VBA_ID_MODULEOFFSET
Definition: vbahelper.hxx:40
const sal_uInt16 VBA_ID_MODULECOOKIE
Definition: vbahelper.hxx:33
const sal_uInt16 VBA_ID_MODULEPRIVATE
Definition: vbahelper.hxx:41
const sal_uInt16 VBA_ID_MODULESTREAMNAME
Definition: vbahelper.hxx:43
const sal_uInt16 VBA_ID_MODULENAMEUNICODE
Definition: vbahelper.hxx:39
const sal_uInt16 VBA_ID_MODULEREADONLY
Definition: vbahelper.hxx:42
const sal_uInt16 VBA_ID_MODULEEND
Definition: vbahelper.hxx:36
css::uno::Sequence< sal_Int8 > StreamDataSequence
sal_Int32 mnType
Stores, which key shortcut maps to which VBA macro method.
Definition: vbamodule.hxx:45
#define SAL_MAX_UINT32
#define OOX_ENSURE_RECORDSIZE(cond)