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 <filter/msfilter/msvbahelper.hxx>
29 #include <oox/helper/binaryinputstream.hxx>
30 #include <oox/helper/storagebase.hxx>
31 #include <oox/helper/textinputstream.hxx>
32 #include <oox/ole/vbahelper.hxx>
33 #include <oox/ole/vbainputstream.hxx>
37 using namespace ::com::sun::star::lang
;
38 using namespace ::com::sun::star::script::vba
;
39 using namespace ::com::sun::star::uno
;
40 using namespace ::com::sun::star
;
42 using ::com::sun::star::awt::KeyEvent
;
44 VbaModule::VbaModule( const Reference
< XComponentContext
>& rxContext
,
45 const Reference
< frame::XModel
>& rxDocModel
,
46 const OUString
& rName
, rtl_TextEncoding eTextEnc
, bool bExecutable
) :
47 mxContext( rxContext
),
48 mxDocModel( rxDocModel
),
50 meTextEnc( eTextEnc
),
51 mnType( script::ModuleType::UNKNOWN
),
52 mnOffset( SAL_MAX_UINT32
),
55 mbExecutable( bExecutable
)
59 void VbaModule::importDirRecords( BinaryInputStream
& rDirStrm
)
61 sal_uInt16 nRecId
= 0;
62 StreamDataSequence aRecData
;
63 while( VbaHelper::readDirRecord( nRecId
, aRecData
, rDirStrm
) && (nRecId
!= VBA_ID_MODULEEND
) )
65 SequenceInputStream
aRecStrm( aRecData
);
66 sal_Int32 nRecSize
= aRecData
.getLength();
69 #define OOX_ENSURE_RECORDSIZE( cond ) OSL_ENSURE( cond, "VbaModule::importDirRecords - invalid record size" )
70 case VBA_ID_MODULENAME
:
71 OSL_FAIL( "VbaModule::importDirRecords - unexpected MODULENAME record" );
72 maName
= aRecStrm
.readCharArrayUC( nRecSize
, meTextEnc
);
74 case VBA_ID_MODULENAMEUNICODE
:
76 case VBA_ID_MODULESTREAMNAME
:
77 maStreamName
= aRecStrm
.readCharArrayUC( nRecSize
, meTextEnc
);
78 // Actually the stream name seems the best name to use
79 // the VBA_ID_MODULENAME name can sometimes be the wrong case
80 maName
= maStreamName
;
82 case VBA_ID_MODULESTREAMNAMEUNICODE
:
84 case VBA_ID_MODULEDOCSTRING
:
85 maDocString
= aRecStrm
.readCharArrayUC( nRecSize
, meTextEnc
);
87 case VBA_ID_MODULEDOCSTRINGUNICODE
:
89 case VBA_ID_MODULEOFFSET
:
90 OOX_ENSURE_RECORDSIZE( nRecSize
== 4 );
91 mnOffset
= aRecStrm
.readuInt32();
93 case VBA_ID_MODULEHELPCONTEXT
:
94 OOX_ENSURE_RECORDSIZE( nRecSize
== 4 );
96 case VBA_ID_MODULECOOKIE
:
97 OOX_ENSURE_RECORDSIZE( nRecSize
== 2 );
99 case VBA_ID_MODULETYPEPROCEDURAL
:
100 OOX_ENSURE_RECORDSIZE( nRecSize
== 0 );
101 OSL_ENSURE( mnType
== script::ModuleType::UNKNOWN
, "VbaModule::importDirRecords - multiple module type records" );
102 mnType
= script::ModuleType::NORMAL
;
104 case VBA_ID_MODULETYPEDOCUMENT
:
105 OOX_ENSURE_RECORDSIZE( nRecSize
== 0 );
106 OSL_ENSURE( mnType
== script::ModuleType::UNKNOWN
, "VbaModule::importDirRecords - multiple module type records" );
107 mnType
= script::ModuleType::DOCUMENT
;
109 case VBA_ID_MODULEREADONLY
:
110 OOX_ENSURE_RECORDSIZE( nRecSize
== 0 );
113 case VBA_ID_MODULEPRIVATE
:
114 OOX_ENSURE_RECORDSIZE( nRecSize
== 0 );
118 OSL_FAIL( "VbaModule::importDirRecords - unknown module record" );
119 #undef OOX_ENSURE_RECORDSIZE
122 OSL_ENSURE( !maName
.isEmpty(), "VbaModule::importDirRecords - missing module name" );
123 OSL_ENSURE( !maStreamName
.isEmpty(), "VbaModule::importDirRecords - missing module stream name" );
124 OSL_ENSURE( mnType
!= script::ModuleType::UNKNOWN
, "VbaModule::importDirRecords - missing module type" );
125 OSL_ENSURE( mnOffset
< SAL_MAX_UINT32
, "VbaModule::importDirRecords - missing module stream offset" );
128 void VbaModule::createAndImportModule( StorageBase
& rVbaStrg
,
129 const Reference
< container::XNameContainer
>& rxBasicLib
,
130 const Reference
< container::XNameAccess
>& rxDocObjectNA
) const
132 OUString aVBASourceCode
= readSourceCode( rVbaStrg
);
133 createModule( aVBASourceCode
, rxBasicLib
, rxDocObjectNA
);
136 void VbaModule::createEmptyModule( const Reference
< container::XNameContainer
>& rxBasicLib
,
137 const Reference
< container::XNameAccess
>& rxDocObjectNA
) const
139 createModule( OUString(), rxBasicLib
, rxDocObjectNA
);
142 OUString
VbaModule::readSourceCode( StorageBase
& rVbaStrg
) const
144 OUStringBuffer
aSourceCode(512);
145 static const char sUnmatchedRemovedTag
[] = "Rem removed unmatched Sub/End: ";
146 if( !maStreamName
.isEmpty() && (mnOffset
!= SAL_MAX_UINT32
) )
148 BinaryXInputStream
aInStrm( rVbaStrg
.openInputStream( maStreamName
), true );
149 OSL_ENSURE( !aInStrm
.isEof(), "VbaModule::readSourceCode - cannot open module stream" );
150 // skip the 'performance cache' stored before the actual source code
151 aInStrm
.seek( mnOffset
);
152 // if stream is still valid, load the source code
153 if( !aInStrm
.isEof() )
155 // decompression starts at current stream position of aInStrm
156 VbaInputStream
aVbaStrm( aInStrm
);
157 // load the source code line-by-line, with some more processing
158 TextInputStream
aVbaTextStrm( mxContext
, aVbaStrm
, meTextEnc
);
164 ProcedurePair() : bInProcedure( false ), nPos( 0 ) {};
167 while( !aVbaTextStrm
.isEof() )
169 OUString aCodeLine
= aVbaTextStrm
.readLine();
170 if( aCodeLine
.match( "Attribute " ) )
173 int index
= aCodeLine
.indexOf( ".VB_ProcData.VB_Invoke_Func = " );
177 // 'Attribute Procedure.VB_ProcData.VB_Invoke_Func = "*\n14"'
178 // where 'Procedure' is the procedure name and '*' is the shortcut key
179 // note: his is only relevant for Excel, seems that
180 // word doesn't store the shortcut in the module
182 int nSpaceIndex
= aCodeLine
.indexOf(' ');
183 OUString sProc
= aCodeLine
.copy( nSpaceIndex
+ 1, index
- nSpaceIndex
- 1);
184 // for Excel short cut key seems limited to cntrl+'a-z, A-Z'
185 OUString sKey
= aCodeLine
.copy( aCodeLine
.lastIndexOf("= ") + 3, 1 );
186 // only alpha key valid for key shortcut, however the api will accept other keys
187 if ( rtl::isAsciiAlpha( sKey
[ 0 ] ) )
189 // cntrl modifier is explicit ( but could be cntrl+shift ), parseKeyEvent
190 // will handle and uppercase letter appropriately
191 OUString sApiKey
= "^" + sKey
;
194 KeyEvent aKeyEvent
= ooo::vba::parseKeyEvent( sApiKey
);
195 ooo::vba::applyShortCutKeyBinding( mxDocModel
, aKeyEvent
, sProc
);
197 catch (const Exception
&)
205 // Hack here to weed out any unmatched End Sub / Sub Foo statements.
206 // The behaviour of the vba ide practically guarantees the case and
207 // spacing of Sub statement(s). However, indentation can be arbitrary hence
209 OUString
trimLine( aCodeLine
.trim() );
210 if ( mbExecutable
&& (
211 trimLine
.match("Sub ") ||
212 trimLine
.match("Public Sub ") ||
213 trimLine
.match("Private Sub ") ||
214 trimLine
.match("Static Sub ") ) )
216 // this should never happen, basic doesn't support nested procedures
217 // first Sub Foo must be bogus
218 if ( procInfo
.bInProcedure
)
220 // comment out the line
221 aSourceCode
.insert( procInfo
.nPos
, sUnmatchedRemovedTag
);
222 // mark location of this Sub
223 procInfo
.nPos
= aSourceCode
.getLength();
227 procInfo
.bInProcedure
= true;
228 procInfo
.nPos
= aSourceCode
.getLength();
231 else if ( mbExecutable
&& aCodeLine
.trim().match("End Sub") )
233 // un-matched End Sub
234 if ( !procInfo
.bInProcedure
)
236 aSourceCode
.append( sUnmatchedRemovedTag
);
240 procInfo
.bInProcedure
= false;
244 // normal source code line
246 aSourceCode
.append( "Rem " );
247 aSourceCode
.append( aCodeLine
).append( '\n' );
252 return aSourceCode
.makeStringAndClear();
255 void VbaModule::createModule( const OUString
& rVBASourceCode
,
256 const Reference
< container::XNameContainer
>& rxBasicLib
,
257 const Reference
< container::XNameAccess
>& rxDocObjectNA
) const
259 if( maName
.isEmpty() )
262 // prepare the Basic module
263 script::ModuleInfo aModuleInfo
;
264 aModuleInfo
.ModuleType
= mnType
;
265 OUStringBuffer
aSourceCode(512);
266 aSourceCode
.append( "Rem Attribute VBA_ModuleType=" );
269 case script::ModuleType::NORMAL
:
270 aSourceCode
.append( "VBAModule" );
272 case script::ModuleType::CLASS
:
273 aSourceCode
.append( "VBAClassModule" );
275 case script::ModuleType::FORM
:
276 aSourceCode
.append( "VBAFormModule" );
277 // hack from old filter, document Basic should know the XModel, but it doesn't
278 aModuleInfo
.ModuleObject
.set( mxDocModel
, UNO_QUERY
);
280 case script::ModuleType::DOCUMENT
:
281 aSourceCode
.append( "VBADocumentModule" );
282 // get the VBA implementation object associated to the document module
283 if( rxDocObjectNA
.is() ) try
285 aModuleInfo
.ModuleObject
.set( rxDocObjectNA
->getByName( maName
), UNO_QUERY
);
287 catch (const Exception
&)
292 aSourceCode
.append( "VBAUnknown" );
294 aSourceCode
.append( '\n' );
297 aSourceCode
.append( "Option VBASupport 1\n" );
298 if( mnType
== script::ModuleType::CLASS
)
299 aSourceCode
.append( "Option ClassModule\n" );
303 // add a subroutine named after the module itself
304 aSourceCode
.append( "Sub " ).
305 append( maName
.replace( ' ', '_' ) ).append( '\n' );
308 // append passed VBA source code
309 aSourceCode
.append( rVBASourceCode
);
311 // close the subroutine named after the module
313 aSourceCode
.append( "End Sub\n" );
315 // insert extended module info
318 Reference
< XVBAModuleInfo
> xVBAModuleInfo( rxBasicLib
, UNO_QUERY_THROW
);
319 xVBAModuleInfo
->insertModuleInfo( maName
, aModuleInfo
);
321 catch (const Exception
&)
325 // insert the module into the passed Basic library
328 rxBasicLib
->insertByName( maName
, Any( aSourceCode
.makeStringAndClear() ) );
330 catch (const Exception
&)
332 OSL_FAIL( "VbaModule::createModule - cannot insert module into library" );
336 } // namespace oox::ole
338 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */