Debian Codegraph @

basic/source/classes/sb.cxx

raw
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 <sb.hxx>
21 #include <o3tl/safeint.hxx>
22 #include <osl/diagnose.h>
23 #include <rtl/ustrbuf.hxx>
24 #include <tools/stream.hxx>
25 #include <tools/debug.hxx>
26 #include <comphelper/solarmutex.hxx>
27 #include <basic/sbx.hxx>
28 #include <vcl/svapp.hxx>
29 #include <comphelper/processfactory.hxx>
30 #include <image.hxx>
31 #include <sbunoobj.hxx>
32 #include <sbjsmeth.hxx>
33 #include <sbjsmod.hxx>
34 #include <sbintern.hxx>
35 #include <runtime.hxx>
36 #include <basic/sberrors.hxx>
37 #include <basic/sbuno.hxx>
38 #include <sbprop.hxx>
39 #include <sbobjmod.hxx>
40 #include <stdobj.hxx>
41 #include <basic.hrc>
42 #include <cppuhelper/implbase.hxx>
43 #include <com/sun/star/lang/XMultiServiceFactory.hpp>
44 #include <com/sun/star/util/XCloseBroadcaster.hpp>
45 #include <com/sun/star/util/XCloseListener.hpp>
46 #include <sal/log.hxx>
47 #include <errobject.hxx>
48 #include <memory>
49 #include <unordered_map>
50
51 #include <com/sun/star/script/ModuleType.hpp>
52 #include <com/sun/star/script/ModuleInfo.hpp>
53
54 #include <strings.hrc>
55
56 using namespace ::com::sun::star::script;
57
58 constexpr OUString SB_RTLNAME = u"@SBRTL"_ustr;
59 // i#i68894#
60 using namespace ::com::sun::star;
61 using namespace ::com::sun::star::uno;
62 using com::sun::star::uno::Reference;
63 using com::sun::star::uno::Any;
64 using com::sun::star::uno::UNO_QUERY;
65 using com::sun::star::lang::XMultiServiceFactory;
66
67
68 class DocBasicItem : public ::cppu::WeakImplHelper< util::XCloseListener >
69 {
70 public:
71 explicit DocBasicItem( StarBASIC& rDocBasic );
72 virtual ~DocBasicItem() override;
73
74 const SbxObjectRef& getClassModules() const { return mxClassModules; }
75 bool isDocClosed() const { return mbDocClosed; }
76
77 void clearDependingVarsOnDelete( StarBASIC& rDeletedBasic );
78
79 void startListening();
80 void stopListening();
81
82 void setDisposed( bool bDisposed )
83 {
84 mbDisposed = bDisposed;
85 }
86
87 virtual void SAL_CALL queryClosing( const lang::EventObject& rSource, sal_Bool bGetsOwnership ) override;
88 virtual void SAL_CALL notifyClosing( const lang::EventObject& rSource ) override;
89 virtual void SAL_CALL disposing( const lang::EventObject& rSource ) override;
90
91 private:
92 StarBASIC& mrDocBasic;
93 SbxObjectRef mxClassModules;
94 bool mbDocClosed;
95 bool mbDisposed;
96 };
97
98
99 DocBasicItem::DocBasicItem( StarBASIC& rDocBasic ) :
100 mrDocBasic( rDocBasic ),
101 mxClassModules( new SbxObject( OUString() ) ),
102 mbDocClosed( false ),
103 mbDisposed( false )
104 {
105 }
106
107 DocBasicItem::~DocBasicItem()
108 {
109 // tdf#90969 HACK: don't use SolarMutexGuard - there is a horrible global
110 // map GaDocBasicItems holding instances, and these get deleted from exit
111 // handlers, when the SolarMutex is already dead
112 comphelper::SolarMutex *pSolarMutex = comphelper::SolarMutex::get();
113 if ( pSolarMutex )
114 pSolarMutex->acquire();
115
116 try
117 {
118 stopListening();
119 mxClassModules.clear(); // release with SolarMutex locked
120 }
121 catch (...)
122 {
123 assert(false);
124 }
125
126 pSolarMutex = comphelper::SolarMutex::get();
127 if ( pSolarMutex )
128 pSolarMutex->release();
129 }
130
131 void DocBasicItem::clearDependingVarsOnDelete( StarBASIC& rDeletedBasic )
132 {
133 mrDocBasic.implClearDependingVarsOnDelete( &rDeletedBasic );
134 }
135
136 void DocBasicItem::startListening()
137 {
138 Any aThisComp;
139 mrDocBasic.GetUNOConstant( u"ThisComponent"_ustr, aThisComp );
140 Reference< util::XCloseBroadcaster > xCloseBC( aThisComp, UNO_QUERY );
141 mbDisposed = !xCloseBC.is();
142 if( xCloseBC.is() )
143 {
144 try { xCloseBC->addCloseListener( this ); } catch(const uno::Exception& ) {}
145 }
146 }
147
148 void DocBasicItem::stopListening()
149 {
150 if( mbDisposed ) return;
151 mbDisposed = true;
152 Any aThisComp;
153 if (!mrDocBasic.GetUNOConstant(u"ThisComponent"_ustr, aThisComp))
154 return;
155
156 Reference< util::XCloseBroadcaster > xCloseBC( aThisComp, UNO_QUERY );
157 if( xCloseBC.is() )
158 {
159 try { xCloseBC->removeCloseListener( this ); } catch(const uno::Exception& ) {}
160 }
161 }
162
163 void SAL_CALL DocBasicItem::queryClosing( const lang::EventObject& /*rSource*/, sal_Bool /*bGetsOwnership*/ )
164 {
165 }
166
167 void SAL_CALL DocBasicItem::notifyClosing( const lang::EventObject& /*rEvent*/ )
168 {
169 stopListening();
170 mbDocClosed = true;
171 }
172
173 void SAL_CALL DocBasicItem::disposing( const lang::EventObject& /*rEvent*/ )
174 {
175 stopListening();
176 }
177
178
179 namespace {
180
181 typedef ::rtl::Reference< DocBasicItem > DocBasicItemRef;
182
183 std::unordered_map< const StarBASIC *, DocBasicItemRef > gaDocBasicItems;
184
185 const DocBasicItem* lclFindDocBasicItem( const StarBASIC* pDocBasic )
186 {
187 auto it = gaDocBasicItems.find( pDocBasic );
188 auto end = gaDocBasicItems.end();
189 return (it != end) ? it->second.get() : nullptr;
190 }
191
192 void lclInsertDocBasicItem( StarBASIC& rDocBasic )
193 {
194 DocBasicItemRef& rxDocBasicItem = gaDocBasicItems[ &rDocBasic ];
195 rxDocBasicItem.set( new DocBasicItem( rDocBasic ) );
196 rxDocBasicItem->startListening();
197 }
198
199 void lclRemoveDocBasicItem( StarBASIC& rDocBasic )
200 {
201 auto it = gaDocBasicItems.find( &rDocBasic );
202 if( it != gaDocBasicItems.end() )
203 {
204 it->second->stopListening();
205 gaDocBasicItems.erase( it );
206 }
207 for( auto& rEntry : gaDocBasicItems )
208 {
209 rEntry.second->clearDependingVarsOnDelete( rDocBasic );
210 }
211 }
212
213 StarBASIC* lclGetDocBasicForModule( SbModule* pModule )
214 {
215 StarBASIC* pRetBasic = nullptr;
216 SbxObject* pCurParent = pModule;
217 while( pCurParent->GetParent() != nullptr )
218 {
219 pCurParent = pCurParent->GetParent();
220 StarBASIC* pDocBasic = dynamic_cast<StarBASIC*>( pCurParent );
221 if( pDocBasic != nullptr && pDocBasic->IsDocBasic() )
222 {
223 pRetBasic = pDocBasic;
224 break;
225 }
226 }
227 return pRetBasic;
228 }
229
230 } // namespace
231
232
233 SbxObject* StarBASIC::getVBAGlobals( )
234 {
235 if ( !pVBAGlobals.is() )
236 {
237 Any aThisDoc;
238 if ( GetUNOConstant(u"ThisComponent"_ustr, aThisDoc) )
239 {
240 Reference< XMultiServiceFactory > xDocFac( aThisDoc, UNO_QUERY );
241 if ( xDocFac.is() )
242 {
243 try
244 {
245 xDocFac->createInstance(u"ooo.vba.VBAGlobals"_ustr);
246 }
247 catch(const Exception& )
248 {
249 // Ignore
250 }
251 }
252 }
253 pVBAGlobals = static_cast<SbUnoObject*>(Find( u"VBAGlobals"_ustr , SbxClassType::DontCare ));
254 }
255 return pVBAGlobals.get();
256 }
257
258 // i#i68894#
259 SbxVariable* StarBASIC::VBAFind( const OUString& rName, SbxClassType t )
260 {
261 if( rName == "ThisComponent" )
262 {
263 return nullptr;
264 }
265 // rename to init globals
266 if ( getVBAGlobals( ) )
267 {
268 return pVBAGlobals->Find( rName, t );
269 }
270 return nullptr;
271 }
272
273 namespace {
274
275 // Create array for conversion SFX <-> VB error code
276 struct SFX_VB_ErrorItem
277 {
278 sal_uInt16 nErrorVB;
279 ErrCode nErrorSFX;
280 };
281
282 }
283
284 const SFX_VB_ErrorItem SFX_VB_ErrorTab[] =
285 {
286 { 1, ERRCODE_BASIC_EXCEPTION }, // #87844 Map exception to error code 1
287 { 2, ERRCODE_BASIC_SYNTAX },
288 { 3, ERRCODE_BASIC_NO_GOSUB },
289 { 4, ERRCODE_BASIC_REDO_FROM_START },
290 { 5, ERRCODE_BASIC_BAD_ARGUMENT },
291 { 6, ERRCODE_BASIC_MATH_OVERFLOW },
292 { 7, ERRCODE_BASIC_NO_MEMORY },
293 { 8, ERRCODE_BASIC_ALREADY_DIM },
294 { 9, ERRCODE_BASIC_OUT_OF_RANGE },
295 { 10, ERRCODE_BASIC_DUPLICATE_DEF },
296 { 11, ERRCODE_BASIC_ZERODIV },
297 { 12, ERRCODE_BASIC_VAR_UNDEFINED },
298 { 13, ERRCODE_BASIC_CONVERSION },
299 { 14, ERRCODE_BASIC_BAD_PARAMETER },
300 { 18, ERRCODE_BASIC_USER_ABORT },
301 { 20, ERRCODE_BASIC_BAD_RESUME },
302 { 28, ERRCODE_BASIC_STACK_OVERFLOW },
303 { 35, ERRCODE_BASIC_PROC_UNDEFINED },
304 { 48, ERRCODE_BASIC_BAD_DLL_LOAD },
305 { 49, ERRCODE_BASIC_BAD_DLL_CALL },
306 { 51, ERRCODE_BASIC_INTERNAL_ERROR },
307 { 52, ERRCODE_BASIC_BAD_CHANNEL },
308 { 53, ERRCODE_BASIC_FILE_NOT_FOUND },
309 { 54, ERRCODE_BASIC_BAD_FILE_MODE },
310 { 55, ERRCODE_BASIC_FILE_ALREADY_OPEN },
311 { 57, ERRCODE_BASIC_IO_ERROR },
312 { 58, ERRCODE_BASIC_FILE_EXISTS },
313 { 59, ERRCODE_BASIC_BAD_RECORD_LENGTH },
314 { 61, ERRCODE_BASIC_DISK_FULL },
315 { 62, ERRCODE_BASIC_READ_PAST_EOF },
316 { 63, ERRCODE_BASIC_BAD_RECORD_NUMBER },
317 { 67, ERRCODE_BASIC_TOO_MANY_FILES },
318 { 68, ERRCODE_BASIC_NO_DEVICE },
319 { 70, ERRCODE_BASIC_ACCESS_DENIED },
320 { 71, ERRCODE_BASIC_NOT_READY },
321 { 73, ERRCODE_BASIC_NOT_IMPLEMENTED },
322 { 74, ERRCODE_BASIC_DIFFERENT_DRIVE },
323 { 75, ERRCODE_BASIC_ACCESS_ERROR },
324 { 76, ERRCODE_BASIC_PATH_NOT_FOUND },
325 { 91, ERRCODE_BASIC_NO_OBJECT },
326 { 93, ERRCODE_BASIC_BAD_PATTERN },
327 { 94, ERRCODE_BASIC_IS_NULL },
328 { 250, ERRCODE_BASIC_DDE_ERROR },
329 { 280, ERRCODE_BASIC_DDE_WAITINGACK },
330 { 281, ERRCODE_BASIC_DDE_OUTOFCHANNELS },
331 { 282, ERRCODE_BASIC_DDE_NO_RESPONSE },
332 { 283, ERRCODE_BASIC_DDE_MULT_RESPONSES },
333 { 284, ERRCODE_BASIC_DDE_CHANNEL_LOCKED },
334 { 285, ERRCODE_BASIC_DDE_NOTPROCESSED },
335 { 286, ERRCODE_BASIC_DDE_TIMEOUT },
336 { 287, ERRCODE_BASIC_DDE_USER_INTERRUPT },
337 { 288, ERRCODE_BASIC_DDE_BUSY },
338 { 289, ERRCODE_BASIC_DDE_NO_DATA },
339 { 290, ERRCODE_BASIC_DDE_WRONG_DATA_FORMAT },
340 { 291, ERRCODE_BASIC_DDE_PARTNER_QUIT },
341 { 292, ERRCODE_BASIC_DDE_CONV_CLOSED },
342 { 293, ERRCODE_BASIC_DDE_NO_CHANNEL },
343 { 294, ERRCODE_BASIC_DDE_INVALID_LINK },
344 { 295, ERRCODE_BASIC_DDE_QUEUE_OVERFLOW },
345 { 296, ERRCODE_BASIC_DDE_LINK_ALREADY_EST },
346 { 297, ERRCODE_BASIC_DDE_LINK_INV_TOPIC },
347 { 298, ERRCODE_BASIC_DDE_DLL_NOT_FOUND },
348 { 323, ERRCODE_BASIC_CANNOT_LOAD },
349 { 341, ERRCODE_BASIC_BAD_INDEX },
350 { 366, ERRCODE_BASIC_NO_ACTIVE_OBJECT },
351 { 380, ERRCODE_BASIC_BAD_PROP_VALUE },
352 { 382, ERRCODE_BASIC_PROP_READONLY },
353 { 394, ERRCODE_BASIC_PROP_WRITEONLY },
354 { 420, ERRCODE_BASIC_INVALID_OBJECT },
355 { 423, ERRCODE_BASIC_NO_METHOD },
356 { 424, ERRCODE_BASIC_NEEDS_OBJECT },
357 { 425, ERRCODE_BASIC_INVALID_USAGE_OBJECT },
358 { 430, ERRCODE_BASIC_NO_OLE },
359 { 438, ERRCODE_BASIC_BAD_METHOD },
360 { 440, ERRCODE_BASIC_OLE_ERROR },
361 { 445, ERRCODE_BASIC_BAD_ACTION },
362 { 446, ERRCODE_BASIC_NO_NAMED_ARGS },
363 { 447, ERRCODE_BASIC_BAD_LOCALE },
364 { 448, ERRCODE_BASIC_NAMED_NOT_FOUND },
365 { 449, ERRCODE_BASIC_NOT_OPTIONAL },
366 { 450, ERRCODE_BASIC_WRONG_ARGS },
367 { 451, ERRCODE_BASIC_NOT_A_COLL },
368 { 452, ERRCODE_BASIC_BAD_ORDINAL },
369 { 453, ERRCODE_BASIC_DLLPROC_NOT_FOUND },
370 { 460, ERRCODE_BASIC_BAD_CLIPBD_FORMAT },
371 { 951, ERRCODE_BASIC_UNEXPECTED },
372 { 952, ERRCODE_BASIC_EXPECTED },
373 { 953, ERRCODE_BASIC_SYMBOL_EXPECTED },
374 { 954, ERRCODE_BASIC_VAR_EXPECTED },
375 { 955, ERRCODE_BASIC_LABEL_EXPECTED },
376 { 956, ERRCODE_BASIC_LVALUE_EXPECTED },
377 { 957, ERRCODE_BASIC_VAR_DEFINED },
378 { 958, ERRCODE_BASIC_PROC_DEFINED },
379 { 959, ERRCODE_BASIC_LABEL_DEFINED },
380 { 960, ERRCODE_BASIC_UNDEF_VAR },
381 { 961, ERRCODE_BASIC_UNDEF_ARRAY },
382 { 962, ERRCODE_BASIC_UNDEF_PROC },
383 { 963, ERRCODE_BASIC_UNDEF_LABEL },
384 { 964, ERRCODE_BASIC_UNDEF_TYPE },
385 { 965, ERRCODE_BASIC_BAD_EXIT },
386 { 966, ERRCODE_BASIC_BAD_BLOCK },
387 { 967, ERRCODE_BASIC_BAD_BRACKETS },
388 { 968, ERRCODE_BASIC_BAD_DECLARATION },
389 { 969, ERRCODE_BASIC_BAD_PARAMETERS },
390 { 970, ERRCODE_BASIC_BAD_CHAR_IN_NUMBER },
391 { 971, ERRCODE_BASIC_MUST_HAVE_DIMS },
392 { 972, ERRCODE_BASIC_NO_IF },
393 { 973, ERRCODE_BASIC_NOT_IN_SUBR },
394 { 974, ERRCODE_BASIC_NOT_IN_MAIN },
395 { 975, ERRCODE_BASIC_WRONG_DIMS },
396 { 976, ERRCODE_BASIC_BAD_OPTION },
397 { 977, ERRCODE_BASIC_CONSTANT_REDECLARED },
398 { 978, ERRCODE_BASIC_PROG_TOO_LARGE },
399 { 979, ERRCODE_BASIC_NO_STRINGS_ARRAYS },
400 { 1000, ERRCODE_BASIC_PROPERTY_NOT_FOUND },
401 { 1001, ERRCODE_BASIC_METHOD_NOT_FOUND },
402 { 1002, ERRCODE_BASIC_ARG_MISSING },
403 { 1003, ERRCODE_BASIC_BAD_NUMBER_OF_ARGS },
404 { 1004, ERRCODE_BASIC_METHOD_FAILED },
405 { 1005, ERRCODE_BASIC_SETPROP_FAILED },
406 { 1006, ERRCODE_BASIC_GETPROP_FAILED },
407 { 1007, ERRCODE_BASIC_COMPAT },
408 { 0xFFFF, ErrCode(0xFFFFFFFFUL) } // End mark
409 };
410
411 // The StarBASIC factory is a hack. When a SbModule is created, its pointer
412 // is saved and given to the following SbProperties/SbMethods. This restores
413 // the Module-relationship. But it works only when a module is loaded.
414 // Can cause troubles with separately loaded properties!
415
416 SbxBaseRef SbiFactory::Create( sal_uInt16 nSbxId, sal_uInt32 nCreator )
417 {
418 if( nCreator == SBXCR_SBX )
419 {
420 switch( nSbxId )
421 {
422 case SBXID_BASIC:
423 return new StarBASIC( nullptr );
424 case SBXID_BASICMOD:
425 return new SbModule( u""_ustr );
426 case SBXID_BASICPROP:
427 return new SbProperty( u""_ustr, SbxVARIANT, nullptr );
428 case SBXID_BASICMETHOD:
429 return new SbMethod( u""_ustr, SbxVARIANT, nullptr );
430 case SBXID_JSCRIPTMOD:
431 return new SbJScriptModule;
432 case SBXID_JSCRIPTMETH:
433 return new SbJScriptMethod( SbxVARIANT );
434 }
435 }
436 return nullptr;
437 }
438
439 SbxObjectRef SbiFactory::CreateObject( const OUString& rClass )
440 {
441 if( rClass.equalsIgnoreAsciiCase( "StarBASIC" ) )
442 {
443 return new StarBASIC( nullptr );
444 }
445 else if( rClass.equalsIgnoreAsciiCase( "StarBASICModule" ) )
446 {
447 return new SbModule( OUString() );
448 }
449 else if( rClass.equalsIgnoreAsciiCase( "Collection" ) )
450 {
451 return new BasicCollection( u"Collection"_ustr );
452 }
453 else if( rClass.equalsIgnoreAsciiCase( "FileSystemObject" ) )
454 {
455 try
456 {
457 Reference< XMultiServiceFactory > xFactory( comphelper::getProcessServiceFactory(), UNO_SET_THROW );
458 OUString aServiceName(u"ooo.vba.FileSystemObject"_ustr);
459 Reference< XInterface > xInterface( xFactory->createInstance( aServiceName ), UNO_SET_THROW );
460 return new SbUnoObject( aServiceName, uno::Any( xInterface ) );
461 }
462 catch(const Exception& )
463 {
464 }
465 }
466 return nullptr;
467 }
468
469
470 SbxBaseRef SbOLEFactory::Create( sal_uInt16, sal_uInt32 )
471 {
472 // Not supported
473 return nullptr;
474 }
475
476 SbxObjectRef SbOLEFactory::CreateObject( const OUString& rClassName )
477 {
478 SbxObjectRef pRet = createOLEObject_Impl( rClassName );
479 return pRet;
480 }
481
482
483 // SbFormFactory, show user forms by: dim as new <user form name>
484
485 SbxBaseRef SbFormFactory::Create( sal_uInt16, sal_uInt32 )
486 {
487 // Not supported
488 return nullptr;
489 }
490
491 SbxObjectRef SbFormFactory::CreateObject( const OUString& rClassName )
492 {
493 if( SbModule* pMod = GetSbData()->pMod )
494 {
495 if( SbxVariable* pVar = pMod->Find( rClassName, SbxClassType::Object ) )
496 {
497 if( SbUserFormModule* pFormModule = dynamic_cast<SbUserFormModule*>( pVar->GetObject() ) )
498 {
499 bool bInitState = pFormModule->getInitState();
500 if( bInitState )
501 {
502 // Not the first instantiate, reset
503 pFormModule->ResetApiObj( false/*bTriggerTerminateEvent*/ );
504 pFormModule->setInitState( false );
505 }
506 else
507 {
508 pFormModule->Load();
509 }
510 return pFormModule->CreateInstance();
511 }
512 }
513 }
514 return nullptr;
515 }
516
517
518 // SbTypeFactory
519
520 SbxObjectRef cloneTypeObjectImpl( const SbxObject& rTypeObj )
521 {
522 SbxObjectRef pRet = new SbxObject( rTypeObj );
523 pRet->PutObject( pRet.get() );
524
525 // Copy the properties, not only the reference to them
526 SbxArray* pProps = pRet->GetProperties();
527 sal_uInt32 nCount = pProps->Count();
528 for( sal_uInt32 i = 0 ; i < nCount ; i++ )
529 {
530 SbxVariable* pVar = pProps->Get(i);
531 SbxProperty* pProp = dynamic_cast<SbxProperty*>( pVar );
532 if( pProp )
533 {
534 SbxProperty* pNewProp = new SbxProperty( *pProp );
535 SbxDataType eVarType = pVar->GetType();
536 if( eVarType & SbxARRAY )
537 {
538 SbxBase* pParObj = pVar->GetObject();
539 SbxDimArray* pSource = dynamic_cast<SbxDimArray*>( pParObj );
540 SbxDimArray* pDest = new SbxDimArray( pVar->GetType() );
541
542 pDest->setHasFixedSize( pSource && pSource->hasFixedSize() );
543 if (pSource && pSource->GetDims() && pSource->hasFixedSize())
544 {
545 sal_Int32 lb = 0;
546 sal_Int32 ub = 0;
547 for (sal_Int32 j = 1; j <= pSource->GetDims(); ++j)
548 {
549 pSource->GetDim(j, lb, ub);
550 pDest->AddDim(lb, ub);
551 }
552 }
553 else
554 {
555 pDest->unoAddDim(0, -1); // variant array
556 }
557 SbxFlagBits nSavFlags = pVar->GetFlags();
558 pNewProp->ResetFlag( SbxFlagBits::Fixed );
559 // need to reset the FIXED flag
560 // when calling PutObject ( because the type will not match Object )
561 pNewProp->PutObject( pDest );
562 pNewProp->SetFlags( nSavFlags );
563 }
564 if( eVarType == SbxOBJECT )
565 {
566 SbxBase* pObjBase = pVar->GetObject();
567 SbxObject* pSrcObj = dynamic_cast<SbxObject*>( pObjBase );
568 SbxObjectRef pDestObj;
569 if( pSrcObj != nullptr )
570 pDestObj = cloneTypeObjectImpl( *pSrcObj );
571 pNewProp->PutObject( pDestObj.get() );
572 }
573 pProps->PutDirect( pNewProp, i );
574 }
575 }
576 return pRet;
577 }
578
579 SbxBaseRef SbTypeFactory::Create( sal_uInt16, sal_uInt32 )
580 {
581 // Not supported
582 return nullptr;
583 }
584
585 SbxObjectRef SbTypeFactory::CreateObject( const OUString& rClassName )
586 {
587 SbxObjectRef pRet;
588 SbModule* pMod = GetSbData()->pMod;
589 if( pMod )
590 {
591 const SbxObject* pObj = pMod->FindType( rClassName );
592 if( pObj )
593 {
594 pRet = cloneTypeObjectImpl( *pObj );
595 }
596 }
597 return pRet;
598 }
599
600 SbxObjectRef createUserTypeImpl( const OUString& rClassName )
601 {
602 SbxObjectRef pRetObj = GetSbData()->pTypeFac->CreateObject( rClassName );
603 return pRetObj;
604 }
605
606 SbClassModuleObject::SbClassModuleObject(SbModule& rClassModule)
607 : SbModule(rClassModule.GetName())
608 , mrClassModule(rClassModule)
609 , mbInitializeEventDone( false )
610 {
611 aOUSource = rClassModule.aOUSource;
612 aComment = rClassModule.aComment;
613 pImage = rClassModule.pImage;
614 pBreaks = rClassModule.pBreaks;
615
616 SetClassName(rClassModule.GetName());
617
618 // Allow search only internally
619 ResetFlag( SbxFlagBits::GlobalSearch );
620
621 // Copy the methods from original class module
622 SbxArray* pClassMethods = rClassModule.GetMethods().get();
623 sal_uInt32 nMethodCount = pClassMethods->Count();
624 sal_uInt32 i;
625 for( i = 0 ; i < nMethodCount ; i++ )
626 {
627 SbxVariable* pVar = pClassMethods->Get(i);
628
629 // Exclude SbIfaceMapperMethod to copy them in a second step
630 SbIfaceMapperMethod* pIfaceMethod = dynamic_cast<SbIfaceMapperMethod*>( pVar );
631 if( !pIfaceMethod )
632 {
633 SbMethod* pMethod = dynamic_cast<SbMethod*>( pVar );
634 if( pMethod )
635 {
636 SbxFlagBits nFlags_ = pMethod->GetFlags();
637 pMethod->SetFlag( SbxFlagBits::NoBroadcast );
638 SbMethod* pNewMethod = new SbMethod( *pMethod );
639 pNewMethod->ResetFlag( SbxFlagBits::NoBroadcast );
640 pMethod->SetFlags( nFlags_ );
641 pNewMethod->pMod = this;
642 pNewMethod->SetParent( this );
643 pMethods->PutDirect( pNewMethod, i );
644 StartListening(pNewMethod->GetBroadcaster(), DuplicateHandling::Prevent);
645 }
646 }
647 }
648
649 // Copy SbIfaceMapperMethod in a second step to ensure that
650 // the corresponding base methods have already been copied
651 for( i = 0 ; i < nMethodCount ; i++ )
652 {
653 SbxVariable* pVar = pClassMethods->Get(i);
654
655 SbIfaceMapperMethod* pIfaceMethod = dynamic_cast<SbIfaceMapperMethod*>( pVar );
656 if( pIfaceMethod )
657 {
658 SbMethod* pImplMethod = pIfaceMethod->getImplMethod();
659 if( !pImplMethod )
660 {
661 OSL_FAIL( "No ImplMethod" );
662 continue;
663 }
664
665 // Search for own copy of ImplMethod
666 SbxVariable* p = pMethods->Find( pImplMethod->GetName(), SbxClassType::Method );
667 SbMethod* pImplMethodCopy = dynamic_cast<SbMethod*>( p );
668 if( !pImplMethodCopy )
669 {
670 OSL_FAIL( "Found no ImplMethod copy" );
671 continue;
672 }
673 SbIfaceMapperMethod* pNewIfaceMethod =
674 new SbIfaceMapperMethod( pIfaceMethod->GetName(), pImplMethodCopy );
675 pMethods->PutDirect( pNewIfaceMethod, i );
676 }
677 }
678
679 // Copy the properties from original class module
680 SbxArray* pClassProps = rClassModule.GetProperties();
681 sal_uInt32 nPropertyCount = pClassProps->Count();
682 for( i = 0 ; i < nPropertyCount ; i++ )
683 {
684 SbxVariable* pVar = pClassProps->Get(i);
685 SbProcedureProperty* pProcedureProp = dynamic_cast<SbProcedureProperty*>( pVar );
686 if( pProcedureProp )
687 {
688 SbxFlagBits nFlags_ = pProcedureProp->GetFlags();
689 pProcedureProp->SetFlag( SbxFlagBits::NoBroadcast );
690 SbProcedureProperty* pNewProp = new SbProcedureProperty
691 ( pProcedureProp->GetName(), pProcedureProp->GetType() );
692 pNewProp->SetFlags( nFlags_ ); // Copy flags
693 pNewProp->ResetFlag( SbxFlagBits::NoBroadcast ); // except the Broadcast if it was set
694 pProcedureProp->SetFlags( nFlags_ );
695 pProps->PutDirect( pNewProp, i );
696 StartListening(pNewProp->GetBroadcaster(), DuplicateHandling::Prevent);
697 }
698 else
699 {
700 SbxProperty* pProp = dynamic_cast<SbxProperty*>( pVar );
701 if( pProp )
702 {
703 SbxFlagBits nFlags_ = pProp->GetFlags();
704 pProp->SetFlag( SbxFlagBits::NoBroadcast );
705 SbxProperty* pNewProp = new SbxProperty( *pProp );
706
707 // Special handling for modules instances and collections, they need
708 // to be instantiated, otherwise all refer to the same base object
709 SbxDataType eVarType = pProp->GetType();
710 if( eVarType == SbxOBJECT )
711 {
712 SbxBase* pObjBase = pProp->GetObject();
713 SbxObject* pObj = dynamic_cast<SbxObject*>( pObjBase );
714 if( pObj != nullptr )
715 {
716 const OUString& aObjClass = pObj->GetClassName();
717
718 SbClassModuleObject* pClassModuleObj = dynamic_cast<SbClassModuleObject*>( pObjBase );
719 if( pClassModuleObj != nullptr )
720 {
721 SbModule& rLclClassModule = pClassModuleObj->getClassModule();
722 SbClassModuleObject* pNewObj = new SbClassModuleObject(rLclClassModule);
723 pNewObj->SetName( pProp->GetName() );
724 pNewObj->SetParent(rLclClassModule.pParent);
725 pNewProp->PutObject( pNewObj );
726 }
727 else if( aObjClass.equalsIgnoreAsciiCase( "Collection" ) )
728 {
729 BasicCollection* pNewCollection = new BasicCollection( u"Collection"_ustr );
730 pNewCollection->SetName( pProp->GetName() );
731 pNewCollection->SetParent(rClassModule.pParent);
732 pNewProp->PutObject( pNewCollection );
733 }
734 }
735 }
736
737 pNewProp->ResetFlag( SbxFlagBits::NoBroadcast );
738 pNewProp->SetParent( this );
739 pProps->PutDirect( pNewProp, i );
740 pProp->SetFlags( nFlags_ );
741 }
742 }
743 }
744 SetModuleType( ModuleType::CLASS );
745 mbVBASupport = rClassModule.mbVBASupport;
746 }
747
748 SbClassModuleObject::~SbClassModuleObject()
749 {
750 // do not trigger termination event when document is already closed
751 if( StarBASIC::IsRunning() )
752 if( StarBASIC* pDocBasic = lclGetDocBasicForModule( this ) )
753 if( const DocBasicItem* pDocBasicItem = lclFindDocBasicItem( pDocBasic ) )
754 if( !pDocBasicItem->isDocClosed() )
755 triggerTerminateEvent();
756 }
757
758 void SbClassModuleObject::Notify( SfxBroadcaster& rBC, const SfxHint& rHint )
759 {
760 handleProcedureProperties( rBC, rHint );
761 }
762
763 SbxVariable* SbClassModuleObject::Find( const OUString& rName, SbxClassType t )
764 {
765 SbxVariable* pRes = SbxObject::Find( rName, t );
766 if( pRes )
767 {
768 triggerInitializeEvent();
769
770 SbIfaceMapperMethod* pIfaceMapperMethod = dynamic_cast<SbIfaceMapperMethod*>( pRes );
771 if( pIfaceMapperMethod )
772 {
773 pRes = pIfaceMapperMethod->getImplMethod();
774 pRes->SetFlag( SbxFlagBits::ExtFound );
775 }
776 }
777 return pRes;
778 }
779
780 void SbClassModuleObject::triggerInitializeEvent()
781 {
782 if( mbInitializeEventDone )
783 {
784 return;
785 }
786
787 mbInitializeEventDone = true;
788
789 // Search method
790 SbxVariable* pMeth = SbxObject::Find(u"Class_Initialize"_ustr, SbxClassType::Method);
791 if( pMeth )
792 {
793 SbxValues aVals;
794 pMeth->Get( aVals );
795 }
796 }
797
798 void SbClassModuleObject::triggerTerminateEvent()
799 {
800 if( !mbInitializeEventDone || GetSbData()->bRunInit )
801 {
802 return;
803 }
804 // Search method
805 SbxVariable* pMeth = SbxObject::Find(u"Class_Terminate"_ustr, SbxClassType::Method );
806 if( pMeth )
807 {
808 SbxValues aVals;
809 pMeth->Get( aVals );
810 }
811 }
812
813
814 SbClassData::SbClassData()
815 {
816 mxIfaces = new SbxArray();
817 }
818
819 void SbClassData::clear()
820 {
821 mxIfaces->Clear();
822 maRequiredTypes.clear();
823 }
824
825 SbClassFactory::SbClassFactory()
826 {
827 xClassModules = new SbxObject( OUString() );
828 }
829
830 SbClassFactory::~SbClassFactory()
831 {}
832
833 void SbClassFactory::AddClassModule( SbModule* pClassModule )
834 {
835 SbxObjectRef xToUseClassModules = xClassModules;
836
837 if( StarBASIC* pDocBasic = lclGetDocBasicForModule( pClassModule ) )
838 if( const DocBasicItem* pDocBasicItem = lclFindDocBasicItem( pDocBasic ) )
839 xToUseClassModules = pDocBasicItem->getClassModules();
840
841 SbxObject* pParent = pClassModule->GetParent();
842 xToUseClassModules->Insert( pClassModule );
843 pClassModule->SetParent( pParent );
844 }
845
846 void SbClassFactory::RemoveClassModule( SbModule* pClassModule )
847 {
848 xClassModules->Remove( pClassModule );
849 }
850
851 SbxBaseRef SbClassFactory::Create( sal_uInt16, sal_uInt32 )
852 {
853 // Not supported
854 return nullptr;
855 }
856
857 SbxObjectRef SbClassFactory::CreateObject( const OUString& rClassName )
858 {
859 SbxObjectRef xToUseClassModules = xClassModules;
860
861 if( SbModule* pMod = GetSbData()->pMod )
862 {
863 if( StarBASIC* pDocBasic = lclGetDocBasicForModule( pMod ) )
864 {
865 if( const DocBasicItem* pDocBasicItem = lclFindDocBasicItem( pDocBasic ) )
866 {
867 xToUseClassModules = pDocBasicItem->getClassModules();
868 }
869 }
870 }
871 SbxVariable* pVar = xToUseClassModules->Find( rClassName, SbxClassType::Object );
872 SbxObjectRef pRet;
873 if( pVar )
874 {
875 SbModule* pVarMod = static_cast<SbModule*>(pVar);
876 pRet = new SbClassModuleObject(*pVarMod);
877 }
878 return pRet;
879 }
880
881 SbModule* SbClassFactory::FindClass( const OUString& rClassName )
882 {
883 SbxVariable* pVar = xClassModules->Find( rClassName, SbxClassType::DontCare );
884 SbModule* pMod = pVar ? static_cast<SbModule*>(pVar) : nullptr;
885 return pMod;
886 }
887
888 StarBASIC::StarBASIC( StarBASIC* p, bool bIsDocBasic )
889 : SbxObject(u"StarBASIC"_ustr), bDocBasic( bIsDocBasic )
890 {
891 SetParent( p );
892 bNoRtl = bBreak = false;
893 bVBAEnabled = false;
894
895 if( !GetSbData()->nInst++ )
896 {
897 GetSbData()->pSbFac.emplace();
898 AddFactory( &*GetSbData()->pSbFac );
899 GetSbData()->pTypeFac.emplace();
900 AddFactory( &*GetSbData()->pTypeFac );
901 GetSbData()->pClassFac.reset(new SbClassFactory);
902 AddFactory( GetSbData()->pClassFac.get() );
903 GetSbData()->pOLEFac.emplace();
904 AddFactory( &*GetSbData()->pOLEFac );
905 GetSbData()->pFormFac.emplace();
906 AddFactory( &*GetSbData()->pFormFac );
907 GetSbData()->pUnoFac.emplace();
908 AddFactory( &*GetSbData()->pUnoFac );
909 }
910 pRtl = new SbiStdObject(SB_RTLNAME, this );
911 // Search via StarBasic is always global
912 SetFlag( SbxFlagBits::GlobalSearch );
913 pVBAGlobals = nullptr;
914 bQuit = false;
915
916 if( bDocBasic )
917 {
918 lclInsertDocBasicItem( *this );
919 }
920 }
921
922 // #51727 Override SetModified so that the modified state
923 // is not given to the parent
924 void StarBASIC::SetModified( bool b )
925 {
926 SbxBase::SetModified( b );
927 }
928
929 StarBASIC::~StarBASIC()
930 {
931 // Needs to be first action as it can trigger events
932 disposeComVariablesForBasic( this );
933
934 if( !--GetSbData()->nInst )
935 {
936 RemoveFactory( &*GetSbData()->pSbFac );
937 GetSbData()->pSbFac.reset();
938 RemoveFactory( &*GetSbData()->pUnoFac );
939 GetSbData()->pUnoFac.reset();
940 RemoveFactory( &*GetSbData()->pTypeFac );
941 GetSbData()->pTypeFac.reset();
942 RemoveFactory( GetSbData()->pClassFac.get() );
943 GetSbData()->pClassFac.reset();
944 RemoveFactory( &*GetSbData()->pOLEFac );
945 GetSbData()->pOLEFac.reset();
946 RemoveFactory( &*GetSbData()->pFormFac );
947 GetSbData()->pFormFac.reset();
948
949 if( SbiGlobals::pGlobals )
950 {
951 delete SbiGlobals::pGlobals;
952 SbiGlobals::pGlobals = nullptr;
953 }
954 }
955 else if( bDocBasic )
956 {
957 ErrCode eOld = SbxBase::GetError();
958
959 lclRemoveDocBasicItem( *this );
960
961 SbxBase::ResetError();
962 if( eOld != ERRCODE_NONE )
963 {
964 SbxBase::SetError( eOld );
965 }
966 }
967
968 // #100326 Set Parent NULL in registered listeners
969 if( xUnoListeners.is() )
970 {
971 sal_uInt32 uCount = xUnoListeners->Count();
972 for( sal_uInt32 i = 0 ; i < uCount ; i++ )
973 {
974 SbxVariable* pListenerObj = xUnoListeners->Get(i);
975 pListenerObj->SetParent( nullptr );
976 }
977 xUnoListeners = nullptr;
978 }
979
980 clearUnoMethodsForBasic( this );
981 }
982
983 void StarBASIC::implClearDependingVarsOnDelete( StarBASIC* pDeletedBasic )
984 {
985 if( this != pDeletedBasic )
986 {
987 for( const auto& pModule: pModules)
988 {
989 pModule->ClearVarsDependingOnDeletedBasic( pDeletedBasic );
990 }
991 }
992
993 for (sal_uInt32 nObj = 0; nObj < pObjs->Count(); nObj++)
994 {
995 SbxVariable* pVar = pObjs->Get(nObj);
996 StarBASIC* pBasic = dynamic_cast<StarBASIC*>( pVar );
997 if( pBasic && pBasic != pDeletedBasic )
998 {
999 pBasic->implClearDependingVarsOnDelete( pDeletedBasic );
1000 }
1001 }
1002 }
1003
1004
1005 SbModule* StarBASIC::MakeModule( const OUString& rName, const OUString& rSrc )
1006 {
1007 ModuleInfo aInfo;
1008 aInfo.ModuleType = ModuleType::NORMAL;
1009 return MakeModule( rName, aInfo, rSrc );
1010 }
1011 SbModule* StarBASIC::MakeModule( const OUString& rName, const ModuleInfo& mInfo, const OUString& rSrc )
1012 {
1013
1014 SAL_INFO(
1015 "basic",
1016 "create module " << rName << " type mInfo " << mInfo.ModuleType);
1017 SbModule* p = nullptr;
1018 switch ( mInfo.ModuleType )
1019 {
1020 case ModuleType::DOCUMENT:
1021 // In theory we should be able to create Object modules
1022 // in ordinary basic ( in vba mode thought these are create
1023 // by the application/basic and not by the user )
1024 p = new SbObjModule( rName, mInfo, isVBAEnabled() );
1025 break;
1026 case ModuleType::CLASS:
1027 p = new SbModule( rName, isVBAEnabled() );
1028 p->SetModuleType( ModuleType::CLASS );
1029 break;
1030 case ModuleType::FORM:
1031 p = new SbUserFormModule( rName, mInfo, isVBAEnabled() );
1032 break;
1033 default:
1034 p = new SbModule( rName, isVBAEnabled() );
1035 break;
1036 }
1037 p->SetSource( rSrc );
1038 p->SetParent( this );
1039 pModules.emplace_back(p);
1040 SetModified( true );
1041 return p;
1042 }
1043
1044 void StarBASIC::Insert( SbxVariable* pVar )
1045 {
1046 if( auto pModule = dynamic_cast<SbModule*>(pVar) )
1047 {
1048 pModules.emplace_back(pModule);
1049 pVar->SetParent( this );
1050 StartListening(pVar->GetBroadcaster(), DuplicateHandling::Prevent);
1051 }
1052 else
1053 {
1054 bool bWasModified = IsModified();
1055 SbxObject::Insert( pVar );
1056 if( !bWasModified && pVar->IsSet( SbxFlagBits::DontStore ) )
1057 {
1058 SetModified( false );
1059 }
1060 }
1061 }
1062
1063 void StarBASIC::Remove( SbxVariable* pVar )
1064 {
1065 SbModule* pModule = dynamic_cast<SbModule*>(pVar);
1066 if( pModule )
1067 {
1068 // #87540 Can be last reference!
1069 SbModuleRef xVar = pModule;
1070 std::erase(pModules, xVar);
1071 pVar->SetParent( nullptr );
1072 EndListening( pVar->GetBroadcaster() );
1073 }
1074 else
1075 {
1076 SbxObject::Remove( pVar );
1077 }
1078 }
1079
1080 void StarBASIC::Clear()
1081 {
1082 pModules.clear();
1083 }
1084
1085 SbModule* StarBASIC::FindModule( std::u16string_view rName )
1086 {
1087 for (const auto& pModule: pModules)
1088 {
1089 if( pModule->GetName().equalsIgnoreAsciiCase( rName ) )
1090 {
1091 return pModule.get();
1092 }
1093 }
1094 return nullptr;
1095 }
1096
1097
1098 struct ClassModuleRunInitItem
1099 {
1100 SbModule* m_pModule;
1101 bool m_bProcessing;
1102 bool m_bRunInitDone;
1103
1104 ClassModuleRunInitItem()
1105 : m_pModule( nullptr )
1106 , m_bProcessing( false )
1107 , m_bRunInitDone( false )
1108 {}
1109 explicit ClassModuleRunInitItem( SbModule* pModule )
1110 : m_pModule( pModule )
1111 , m_bProcessing( false )
1112 , m_bRunInitDone( false )
1113 {}
1114 };
1115
1116 // Derive from unordered_map type instead of typedef
1117 // to allow forward declaration in sbmod.hxx
1118 class ModuleInitDependencyMap : public
1119 std::unordered_map< OUString, ClassModuleRunInitItem >
1120 {};
1121
1122 void SbModule::implProcessModuleRunInit( ModuleInitDependencyMap& rMap, ClassModuleRunInitItem& rItem )
1123 {
1124 rItem.m_bProcessing = true;
1125
1126 SbModule* pModule = rItem.m_pModule;
1127 if( pModule->pClassData != nullptr )
1128 {
1129 std::vector< OUString >& rReqTypes = pModule->pClassData->maRequiredTypes;
1130 for( const auto& rStr : rReqTypes )
1131 {
1132 // Is required type a class module?
1133 ModuleInitDependencyMap::iterator itFind = rMap.find( rStr );
1134 if( itFind != rMap.end() )
1135 {
1136 ClassModuleRunInitItem& rParentItem = itFind->second;
1137 if( rParentItem.m_bProcessing )
1138 {
1139 // TODO: raise error?
1140 OSL_FAIL( "Cyclic module dependency detected" );
1141 continue;
1142 }
1143
1144 if( !rParentItem.m_bRunInitDone )
1145 {
1146 implProcessModuleRunInit( rMap, rParentItem );
1147 }
1148 }
1149 }
1150 }
1151
1152 pModule->RunInit();
1153 rItem.m_bRunInitDone = true;
1154 rItem.m_bProcessing = false;
1155 }
1156
1157 // Run Init-Code of all modules (including inserted libraries)
1158 void StarBASIC::InitAllModules( StarBASIC const * pBasicNotToInit )
1159 {
1160 SolarMutexGuard guard;
1161
1162 // Init own modules
1163 for (const auto& pModule: pModules)
1164 {
1165 pModule->Compile();
1166 }
1167 // compile modules first then RunInit ( otherwise there is
1168 // can be order dependency, e.g. classmodule A has a member
1169 // of type classmodule B and classmodule B hasn't been compiled yet )
1170
1171 // Consider required types to init in right order. Class modules
1172 // that are required by other modules have to be initialized first.
1173 ModuleInitDependencyMap aMIDMap;
1174 for (const auto& pModule: pModules)
1175 {
1176 OUString aModuleName = pModule->GetName();
1177 if (pModule->isClassModule())
1178 {
1179 aMIDMap[aModuleName] = ClassModuleRunInitItem( pModule.get() );
1180 }
1181 }
1182
1183 for (auto & elem : aMIDMap)
1184 {
1185 ClassModuleRunInitItem& rItem = elem.second;
1186 SbModule::implProcessModuleRunInit( aMIDMap, rItem );
1187 }
1188
1189 // Call RunInit on standard modules
1190 for (const auto& pModule: pModules)
1191 {
1192 if (!pModule->isClassModule())
1193 {
1194 pModule->RunInit();
1195 }
1196 }
1197
1198 // Check all objects if they are BASIC,
1199 // if yes initialize
1200 for (sal_uInt32 nObj = 0; nObj < pObjs->Count(); nObj++)
1201 {
1202 SbxVariable* pVar = pObjs->Get(nObj);
1203 StarBASIC* pBasic = dynamic_cast<StarBASIC*>( pVar );
1204 if( pBasic && pBasic != pBasicNotToInit )
1205 {
1206 pBasic->InitAllModules();
1207 }
1208 }
1209 }
1210
1211 // #88329 Put modules back to not initialised state to
1212 // force reinitialisation at next start
1213 void StarBASIC::DeInitAllModules()
1214 {
1215 // Deinit own modules
1216 for (const auto& pModule: pModules)
1217 {
1218 if( pModule->pImage && !pModule->isClassModule() && dynamic_cast<SbObjModule*>( pModule.get()) == nullptr )
1219 {
1220 pModule->pImage->bInit = false;
1221 }
1222 }
1223
1224 for (sal_uInt32 nObj = 0; nObj < pObjs->Count(); nObj++)
1225 {
1226 SbxVariable* pVar = pObjs->Get(nObj);
1227 StarBASIC* pBasic = dynamic_cast<StarBASIC*>( pVar );
1228 if( pBasic )
1229 {
1230 pBasic->DeInitAllModules();
1231 }
1232 }
1233 }
1234
1235 // This implementation at first searches within the runtime library,
1236 // then it looks for an element within one module. This module can be
1237 // a public var or an entrypoint. If it is not found and we look for a
1238 // method and a module with the given name is found the search continues
1239 // for entrypoint "Main".
1240 // If this fails again a conventional search over objects is performed.
1241 SbxVariable* StarBASIC::Find( const OUString& rName, SbxClassType t )
1242 {
1243 SbxVariable* pRes = nullptr;
1244 SbModule* pNamed = nullptr;
1245 // "Extended" search in Runtime Lib
1246 // but only if SbiRuntime has not set the flag
1247 if( !bNoRtl )
1248 {
1249 if( t == SbxClassType::DontCare || t == SbxClassType::Object )
1250 {
1251 if( rName.equalsIgnoreAsciiCase( SB_RTLNAME ) )
1252 {
1253 pRes = pRtl.get();
1254 }
1255 }
1256 if( !pRes )
1257 {
1258 pRes = static_cast<SbiStdObject*>(pRtl.get())->Find( rName, t );
1259 }
1260 if( pRes )
1261 {
1262 pRes->SetFlag( SbxFlagBits::ExtFound );
1263 }
1264 }
1265 // Search module
1266 if( !pRes )
1267 {
1268 for (const auto& pModule: pModules)
1269 {
1270 if( pModule->IsVisible() )
1271 {
1272 // Remember module for Main() call
1273 // or is the name equal?!?
1274 if( pModule->GetName().equalsIgnoreAsciiCase( rName ) )
1275 {
1276 if( t == SbxClassType::Object || t == SbxClassType::DontCare )
1277 {
1278 pRes = pModule.get(); break;
1279 }
1280 pNamed = pModule.get();
1281 }
1282 // Only variables qualified by the Module Name e.g. Sheet1.foo
1283 // should work for Document && Class type Modules
1284 sal_Int32 nType = pModule->GetModuleType();
1285 if ( nType == ModuleType::DOCUMENT || nType == ModuleType::FORM )
1286 {
1287 continue;
1288 }
1289 // otherwise check if the element is available
1290 // unset GBLSEARCH-Flag (due to recursion)
1291 SbxFlagBits nGblFlag = pModule->GetFlags() & SbxFlagBits::GlobalSearch;
1292 pModule->ResetFlag( SbxFlagBits::GlobalSearch );
1293 pRes = pModule->Find( rName, t );
1294 pModule->SetFlag( nGblFlag );
1295 if( pRes )
1296 {
1297 break;
1298 }
1299 }
1300 }
1301 }
1302 static constexpr OUString aMainStr(u"Main"_ustr);
1303 if( !pRes && pNamed && ( t == SbxClassType::Method || t == SbxClassType::DontCare ) &&
1304 !pNamed->GetName().equalsIgnoreAsciiCase( aMainStr ) )
1305 {
1306 pRes = pNamed->Find( aMainStr, SbxClassType::Method );
1307 }
1308 if( !pRes )
1309 {
1310 pRes = SbxObject::Find( rName, t );
1311 }
1312 return pRes;
1313 }
1314
1315 bool StarBASIC::Call( const OUString& rName, SbxArray* pParam )
1316 {
1317 bool bRes = SbxObject::Call( rName, pParam );
1318 if( !bRes )
1319 {
1320 ErrCode eErr = SbxBase::GetError();
1321 if( eErr != ERRCODE_NONE )
1322 {
1323 RTError(eErr, SbxBase::GetErrorMsg(), 0, 0, 0);
1324 }
1325 SbxBase::ResetError();
1326 }
1327 return bRes;
1328 }
1329
1330 // Find method via name (e.g. query via BASIC IDE)
1331 SbxBase* StarBASIC::FindSBXInCurrentScope( const OUString& rName )
1332 {
1333 if( !GetSbData()->pInst )
1334 {
1335 return nullptr;
1336 }
1337 if( !GetSbData()->pInst->pRun )
1338 {
1339 return nullptr;
1340 }
1341 return GetSbData()->pInst->pRun->FindElementExtern( rName );
1342 }
1343
1344 void StarBASIC::QuitAndExitApplication()
1345 {
1346 Stop();
1347 bQuit = true;
1348 }
1349
1350 void StarBASIC::Stop()
1351 {
1352 SbiInstance* p = GetSbData()->pInst;
1353 if( p )
1354 p->Stop();
1355 }
1356
1357 bool StarBASIC::IsRunning()
1358 {
1359 return GetSbData()->pInst != nullptr;
1360 }
1361
1362 SbMethod* StarBASIC::GetActiveMethod( sal_uInt16 nLevel )
1363 {
1364 if( GetSbData()->pInst )
1365 {
1366 return GetSbData()->pInst->GetCaller( nLevel );
1367 }
1368 else
1369 {
1370 return nullptr;
1371 }
1372 }
1373
1374 SbModule* StarBASIC::GetActiveModule()
1375 {
1376 if( GetSbData()->pInst && !GetSbData()->bCompilerError )
1377 {
1378 return GetSbData()->pInst->GetActiveModule();
1379 }
1380 else
1381 {
1382 return GetSbData()->pCompMod;
1383 }
1384 }
1385
1386 BasicDebugFlags StarBASIC::BreakPoint( sal_Int32 l, sal_Int32 c1, sal_Int32 c2 )
1387 {
1388 SetErrorData( ERRCODE_NONE, l, c1, c2 );
1389 bBreak = true;
1390 if( GetSbData()->aBreakHdl.IsSet() )
1391 {
1392 return GetSbData()->aBreakHdl.Call( this );
1393 }
1394 else
1395 {
1396 return BreakHdl();
1397 }
1398 }
1399
1400 BasicDebugFlags StarBASIC::StepPoint( sal_Int32 l, sal_Int32 c1, sal_Int32 c2 )
1401 {
1402 SetErrorData( ERRCODE_NONE, l, c1, c2 );
1403 bBreak = false;
1404 if( GetSbData()->aBreakHdl.IsSet() )
1405 {
1406 return GetSbData()->aBreakHdl.Call( this );
1407 }
1408 else
1409 {
1410 return BreakHdl();
1411 }
1412 }
1413
1414 BasicDebugFlags StarBASIC::BreakHdl()
1415 {
1416 return aBreakHdl.IsSet() ? aBreakHdl.Call( this ) : BasicDebugFlags::Continue;
1417 }
1418
1419 // Calls for error handler and break handler
1420 sal_uInt16 StarBASIC::GetLine() { return GetSbData()->nLine; }
1421 sal_uInt16 StarBASIC::GetCol1() { return GetSbData()->nCol1; }
1422 sal_uInt16 StarBASIC::GetCol2() { return GetSbData()->nCol2; }
1423
1424 // Specific to error handler
1425 ErrCodeMsg const & StarBASIC::GetErrorCode() { return GetSbData()->nCode; }
1426 const OUString& StarBASIC::GetErrorText() { return GetSbData()->aErrMsg; }
1427
1428 // From 1996-03-29:
1429 // The mapping between the old and the new error codes take place by searching
1430 // through the table SFX_VB_ErrorTab[]. This is indeed not with good performance,
1431 // but it consumes much less memory than corresponding switch blocks.
1432 // Because the conversion of error codes has not to be fast. There is no
1433 // binary search by VB Error -> Error SFX.
1434
1435 // Map back new error codes to old, Sbx-compatible
1436 sal_uInt16 StarBASIC::GetVBErrorCode( ErrCode nError )
1437 {
1438 sal_uInt16 nRet = 0;
1439
1440 if( SbiRuntime::isVBAEnabled() )
1441 {
1442 if ( nError == ERRCODE_BASIC_ARRAY_FIX )
1443 return 10;
1444 else if ( nError == ERRCODE_BASIC_STRING_OVERFLOW )
1445 return 14;
1446 else if ( nError == ERRCODE_BASIC_EXPR_TOO_COMPLEX )
1447 return 16;
1448 else if ( nError == ERRCODE_BASIC_OPER_NOT_PERFORM )
1449 return 17;
1450 else if ( nError == ERRCODE_BASIC_TOO_MANY_DLL )
1451 return 47;
1452 else if ( nError == ERRCODE_BASIC_LOOP_NOT_INIT )
1453 return 92;
1454 else
1455 nRet = 0;
1456 }
1457
1458 // search loop
1459 const SFX_VB_ErrorItem* pErrItem;
1460 sal_uInt16 nIndex = 0;
1461 do
1462 {
1463 pErrItem = SFX_VB_ErrorTab + nIndex;
1464 if( pErrItem->nErrorSFX == nError )
1465 {
1466 nRet = pErrItem->nErrorVB;
1467 break;
1468 }
1469 nIndex++;
1470 }
1471 while( pErrItem->nErrorVB != 0xFFFF ); // up to end mark
1472 return nRet;
1473 }
1474
1475 ErrCode StarBASIC::GetSfxFromVBError( sal_uInt16 nError )
1476 {
1477 ErrCode nRet = ERRCODE_NONE;
1478
1479 if( SbiRuntime::isVBAEnabled() )
1480 {
1481 switch( nError )
1482 {
1483 case 1:
1484 case 2:
1485 case 4:
1486 case 8:
1487 case 12:
1488 case 73:
1489 return ERRCODE_NONE;
1490 case 10:
1491 return ERRCODE_BASIC_ARRAY_FIX;
1492 case 14:
1493 return ERRCODE_BASIC_STRING_OVERFLOW;
1494 case 16:
1495 return ERRCODE_BASIC_EXPR_TOO_COMPLEX;
1496 case 17:
1497 return ERRCODE_BASIC_OPER_NOT_PERFORM;
1498 case 47:
1499 return ERRCODE_BASIC_TOO_MANY_DLL;
1500 case 92:
1501 return ERRCODE_BASIC_LOOP_NOT_INIT;
1502 default:
1503 nRet = ERRCODE_NONE;
1504 }
1505 }
1506 const SFX_VB_ErrorItem* pErrItem;
1507 sal_uInt16 nIndex = 0;
1508 do
1509 {
1510 pErrItem = SFX_VB_ErrorTab + nIndex;
1511 if( pErrItem->nErrorVB == nError )
1512 {
1513 nRet = pErrItem->nErrorSFX;
1514 break;
1515 }
1516 else if( pErrItem->nErrorVB > nError )
1517 {
1518 break; // couldn't found anymore
1519 }
1520 nIndex++;
1521 }
1522 while( pErrItem->nErrorVB != 0xFFFF ); // up to end mark
1523 return nRet;
1524 }
1525
1526 // set Error- / Break-data
1527 void StarBASIC::SetErrorData( const ErrCodeMsg& nCode, sal_uInt16 nLine,
1528 sal_uInt16 nCol1, sal_uInt16 nCol2 )
1529 {
1530 SbiGlobals& aGlobals = *GetSbData();
1531 aGlobals.nCode = nCode;
1532 aGlobals.nLine = nLine;
1533 aGlobals.nCol1 = nCol1;
1534 aGlobals.nCol2 = nCol2;
1535 }
1536
1537 void StarBASIC::MakeErrorText( ErrCode nId, std::u16string_view aMsg )
1538 {
1539 SolarMutexGuard aSolarGuard;
1540 sal_uInt16 nOldID = GetVBErrorCode( nId );
1541
1542 TranslateId pErrorMsg;
1543 for (std::pair<TranslateId, ErrCode> const *pItem = RID_BASIC_START; pItem->second; ++pItem)
1544 {
1545 if (nId == pItem->second)
1546 {
1547 pErrorMsg = pItem->first;
1548 break;
1549 }
1550 }
1551
1552 if (pErrorMsg)
1553 {
1554 // merge message with additional text
1555 OUString sError = BasResId(pErrorMsg);
1556 OUStringBuffer aMsg1(sError);
1557 // replace argument placeholder with %s
1558 OUString aSrgStr( u"$(ARG1)"_ustr );
1559 sal_Int32 nResult = sError.indexOf(aSrgStr);
1560
1561 if( nResult >= 0 )
1562 {
1563 aMsg1.remove(nResult, aSrgStr.getLength());
1564 aMsg1.insert(nResult, aMsg);
1565 }
1566 else if (!aMsg.empty())
1567 {
1568 // tdf#123144 - create a meaningful error message
1569 aMsg1 = BasResId(STR_ADDITIONAL_INFO)
1570 .replaceFirst("$ERR", aMsg1)
1571 .replaceFirst("$MSG", aMsg);
1572 }
1573 GetSbData()->aErrMsg = aMsg1.makeStringAndClear();
1574 }
1575 // tdf#123144 - don't use an artificial error message if there is a custom one
1576 else if (!aMsg.empty())
1577 {
1578 GetSbData()->aErrMsg = aMsg;
1579 }
1580 else if( nOldID != 0 )
1581 {
1582 GetSbData()->aErrMsg = "Error " + OUString::number(nOldID) +
1583 ": No error text available!";
1584 }
1585 else
1586 {
1587 GetSbData()->aErrMsg.clear();
1588 }
1589 }
1590
1591 bool StarBASIC::CError( ErrCode code, const OUString& rMsg,
1592 sal_Int32 l, sal_Int32 c1, sal_Int32 c2 )
1593 {
1594 SolarMutexGuard aSolarGuard;
1595
1596 // compiler error during runtime -> stop program
1597 if( IsRunning() )
1598 {
1599 // #109018 Check if running Basic is affected
1600 StarBASIC* pStartedBasic = GetSbData()->pInst->GetBasic();
1601 if( pStartedBasic != this )
1602 {
1603 return false;
1604 }
1605 Stop();
1606 }
1607
1608 // set flag, so that GlobalRunInit notice the error
1609 GetSbData()->bGlobalInitErr = true;
1610
1611 // tinker the error message
1612 MakeErrorText( code, rMsg );
1613
1614 // Implementation of the code for the string transport to SFX-Error
1615 ErrCodeMsg nErr = code;
1616 if( !rMsg.isEmpty() )
1617 {
1618 nErr = ErrCodeMsg( code, rMsg );
1619 }
1620 SetErrorData( nErr, l, c1, c2 );
1621 GetSbData()->bCompilerError = true;
1622 bool bRet;
1623 if( GetSbData()->aErrHdl.IsSet() )
1624 {
1625 bRet = GetSbData()->aErrHdl.Call( this );
1626 }
1627 else
1628 {
1629 bRet = ErrorHdl();
1630 }
1631 GetSbData()->bCompilerError = false; // only true for error handler
1632 return bRet;
1633 }
1634
1635 bool StarBASIC::RTError( ErrCode code, const OUString& rMsg, sal_Int32 l, sal_Int32 c1, sal_Int32 c2 )
1636 {
1637 SolarMutexGuard aSolarGuard;
1638
1639 ErrCode c = code;
1640 if( c.GetClass() == ErrCodeClass::Compiler )
1641 {
1642 c = ERRCODE_NONE;
1643 }
1644 MakeErrorText( c, rMsg );
1645
1646 // Implementation of the code for the string transport to SFX-Error
1647 ErrCodeMsg nErr = code;
1648 if( !rMsg.isEmpty() )
1649 {
1650 // very confusing, even though MakeErrorText sets up the error text
1651 // seems that this is not used ( if rMsg already has content )
1652 // In the case of VBA MakeErrorText also formats the error to be a little more
1653 // like vba ( adds an error number etc )
1654 if ( SbiRuntime::isVBAEnabled() && ( code == ERRCODE_BASIC_COMPAT ) )
1655 {
1656 OUString aTmp = "\'" + OUString::number(SbxErrObject::getUnoErrObject()->getNumber()) +
1657 "\'\n" + (!GetSbData()->aErrMsg.isEmpty() ? GetSbData()->aErrMsg : rMsg);
1658 nErr = ErrCodeMsg( code, aTmp );
1659 }
1660 else
1661 {
1662 nErr = ErrCodeMsg( code, rMsg );
1663 }
1664 }
1665
1666 SetErrorData( nErr, l, c1, c2 );
1667 if( GetSbData()->aErrHdl.IsSet() )
1668 {
1669 return GetSbData()->aErrHdl.Call( this );
1670 }
1671 else
1672 {
1673 return ErrorHdl();
1674 }
1675 }
1676
1677 void StarBASIC::Error( ErrCode n, const OUString& rMsg )
1678 {
1679 if( GetSbData()->pInst )
1680 {
1681 GetSbData()->pInst->Error( n, rMsg );
1682 }
1683 }
1684
1685 void StarBASIC::FatalError( ErrCode n )
1686 {
1687 if( GetSbData()->pInst )
1688 {
1689 GetSbData()->pInst->FatalError( n );
1690 }
1691 }
1692
1693 void StarBASIC::FatalError( ErrCode _errCode, const OUString& _details )
1694 {
1695 if( GetSbData()->pInst )
1696 {
1697 GetSbData()->pInst->FatalError( _errCode, _details );
1698 }
1699 }
1700
1701 ErrCode StarBASIC::GetErrBasic()
1702 {
1703 if( GetSbData()->pInst )
1704 {
1705 return GetSbData()->pInst->GetErr();
1706 }
1707 else
1708 {
1709 return ERRCODE_NONE;
1710 }
1711 }
1712
1713 // make the additional message for the RTL function error accessible
1714 const OUString & StarBASIC::GetErrorMsg()
1715 {
1716 if( GetSbData()->pInst )
1717 {
1718 return GetSbData()->pInst->GetErrorMsg();
1719 }
1720 else
1721 {
1722 return EMPTY_OUSTRING;
1723 }
1724 }
1725
1726 sal_Int32 StarBASIC::GetErl()
1727 {
1728 if( GetSbData()->pInst )
1729 {
1730 return GetSbData()->pInst->GetErl();
1731 }
1732 else
1733 {
1734 return 0;
1735 }
1736 }
1737
1738 bool StarBASIC::ErrorHdl()
1739 {
1740 return aErrorHdl.Call( this );
1741 }
1742
1743 Link<StarBASIC*,bool> const & StarBASIC::GetGlobalErrorHdl()
1744 {
1745 return GetSbData()->aErrHdl;
1746 }
1747
1748 void StarBASIC::SetGlobalErrorHdl( const Link<StarBASIC*,bool>& rLink )
1749 {
1750 GetSbData()->aErrHdl = rLink;
1751 }
1752
1753 void StarBASIC::SetGlobalBreakHdl( const Link<StarBASIC*,BasicDebugFlags>& rLink )
1754 {
1755 GetSbData()->aBreakHdl = rLink;
1756 }
1757
1758 SbxArrayRef const & StarBASIC::getUnoListeners()
1759 {
1760 if( !xUnoListeners.is() )
1761 {
1762 xUnoListeners = new SbxArray();
1763 }
1764 return xUnoListeners;
1765 }
1766
1767
1768 bool StarBASIC::LoadData( SvStream& r, sal_uInt16 nVer )
1769 {
1770 if( !SbxObject::LoadData( r, nVer ) )
1771 {
1772 return false;
1773 }
1774 // #95459 Delete dialogs, otherwise endless recursion
1775 // in SbxVariable::GetType() if dialogs are accessed
1776 sal_uInt32 nObjCount = pObjs->Count();
1777 std::unique_ptr<SbxVariable*[]> ppDeleteTab(new SbxVariable*[ nObjCount ]);
1778 sal_uInt32 nObj;
1779
1780 for( nObj = 0 ; nObj < nObjCount ; nObj++ )
1781 {
1782 SbxVariable* pVar = pObjs->Get(nObj);
1783 StarBASIC* pBasic = dynamic_cast<StarBASIC*>( pVar );
1784 ppDeleteTab[nObj] = pBasic ? nullptr : pVar;
1785 }
1786 for( nObj = 0 ; nObj < nObjCount ; nObj++ )
1787 {
1788 SbxVariable* pVar = ppDeleteTab[nObj];
1789 if( pVar )
1790 {
1791 pObjs->Remove( pVar );
1792 }
1793 }
1794 ppDeleteTab.reset();
1795
1796 sal_uInt16 nMod(0);
1797 pModules.clear();
1798 r.ReadUInt16( nMod );
1799 const size_t nMinSbxSize(14);
1800 const size_t nMaxPossibleEntries = r.remainingSize() / nMinSbxSize;
1801 if (nMod > nMaxPossibleEntries)
1802 {
1803 nMod = nMaxPossibleEntries;
1804 SAL_WARN("basic", "Parsing error: " << nMaxPossibleEntries <<
1805 " max possible entries, but " << nMod << " claimed, truncating");
1806 }
1807 for (sal_uInt16 i = 0; i < nMod; ++i)
1808 {
1809 SbxBaseRef pBase = SbxBase::Load( r );
1810 SbModule* pMod = dynamic_cast<SbModule*>(pBase.get());
1811 if( !pMod )
1812 {
1813 return false;
1814 }
1815 else if( dynamic_cast<const SbJScriptModule*>( pMod) != nullptr )
1816 {
1817 // assign Ref, so that pMod will be deleted
1818 SbModuleRef xDeleteRef = pMod;
1819 }
1820 else
1821 {
1822 pMod->SetParent( this );
1823 pModules.emplace_back(pMod );
1824 }
1825 }
1826 // HACK for SFX-Bullshit!
1827 SbxVariable* p = Find( u"FALSE"_ustr, SbxClassType::Property );
1828 if( p )
1829 {
1830 Remove( p );
1831 }
1832 p = Find( u"TRUE"_ustr, SbxClassType::Property );
1833 if( p )
1834 {
1835 Remove( p );
1836 }
1837 // End of the hacks!
1838 // Search via StarBASIC is at all times global
1839 DBG_ASSERT( IsSet( SbxFlagBits::GlobalSearch ), "Basic loaded without GBLSEARCH" );
1840 SetFlag( SbxFlagBits::GlobalSearch );
1841 return true;
1842 }
1843
1844 std::pair<bool, sal_uInt32> StarBASIC::StoreData( SvStream& r ) const
1845 {
1846 auto [bSuccess, nVersion] = SbxObject::StoreData(r);
1847 if( !bSuccess )
1848 {
1849 return { false, 0 };
1850 }
1851 assert(pModules.size() < SAL_MAX_UINT16);
1852 r.WriteUInt16( static_cast<sal_uInt16>(pModules.size()));
1853 for( const auto& rpModule: pModules )
1854 {
1855 const auto [bSuccessModule, nVersionModule] = rpModule->Store(r);
1856 if( !bSuccessModule )
1857 {
1858 return { false, 0 };
1859 }
1860 else if (nVersionModule > nVersion)
1861 {
1862 nVersion = nVersionModule;
1863 }
1864 }
1865 return { true, nVersion };
1866 }
1867
1868 bool StarBASIC::GetUNOConstant( const OUString& rName, css::uno::Any& aOut )
1869 {
1870 bool bRes = false;
1871 SbUnoObject* pGlobs = dynamic_cast<SbUnoObject*>( Find( rName, SbxClassType::DontCare ) );
1872 if ( pGlobs )
1873 {
1874 aOut = pGlobs->getUnoAny();
1875 bRes = true;
1876 }
1877 return bRes;
1878 }
1879
1880 Reference< frame::XModel > StarBASIC::GetModelFromBasic( SbxObject* pBasic )
1881 {
1882 OSL_PRECOND( pBasic != nullptr, "getModelFromBasic: illegal call!" );
1883 if ( !pBasic )
1884 {
1885 return nullptr;
1886 }
1887 // look for the ThisComponent variable, first in the parent (which
1888 // might be the document's Basic), then in the parent's parent (which might be
1889 // the application Basic)
1890 static constexpr OUStringLiteral sThisComponent( u"ThisComponent");
1891 SbxVariable* pThisComponent = nullptr;
1892
1893 SbxObject* pLookup = pBasic->GetParent();
1894 while ( pLookup && !pThisComponent )
1895 {
1896 pThisComponent = pLookup->Find( sThisComponent, SbxClassType::Object );
1897 pLookup = pLookup->GetParent();
1898 }
1899 if ( !pThisComponent )
1900 {
1901 SAL_WARN("basic", "Failed to get ThisComponent");
1902 // the application Basic, at the latest, should have this variable
1903 return nullptr;
1904 }
1905
1906 Any aThisComponentAny( sbxToUnoValue( pThisComponent ) );
1907 Reference< frame::XModel > xModel( aThisComponentAny, UNO_QUERY );
1908 if ( !xModel.is() )
1909 {
1910 // it's no XModel. Okay, ThisComponent nowadays is allowed to be a controller.
1911 Reference< frame::XController > xController( aThisComponentAny, UNO_QUERY );
1912 if ( xController.is() )
1913 {
1914 xModel = xController->getModel();
1915 }
1916 }
1917 if ( !xModel.is() )
1918 {
1919 return nullptr;
1920 }
1921
1922 return xModel;
1923 }
1924
1925 void StarBASIC::DetachAllDocBasicItems()
1926 {
1927 for (auto const& item : gaDocBasicItems)
1928 {
1929 DocBasicItemRef xItem = item.second;
1930 xItem->setDisposed(true);
1931 }
1932 }
1933
1934 // #118116 Implementation Collection object
1935
1936
1937 // [-loplugin:ostr]
1938 constexpr OUStringLiteral pCountStr = u"Count";
1939 // [-loplugin:ostr]
1940 constexpr OUStringLiteral pAddStr = u"Add";
1941 // [-loplugin:ostr]
1942 constexpr OUStringLiteral pItemStr = u"Item";
1943 // [-loplugin:ostr]
1944 constexpr OUStringLiteral pRemoveStr = u"Remove";
1945 constexpr sal_uInt16 nCountHash = SbxVariable::MakeHashCode(pCountStr);
1946 constexpr sal_uInt16 nAddHash = SbxVariable::MakeHashCode(pAddStr);
1947 constexpr sal_uInt16 nItemHash = SbxVariable::MakeHashCode(pItemStr);
1948 constexpr sal_uInt16 nRemoveHash = SbxVariable::MakeHashCode(pRemoveStr);
1949
1950 SbxInfoRef BasicCollection::xAddInfo;
1951 SbxInfoRef BasicCollection::xItemInfo;
1952
1953 BasicCollection::BasicCollection( const OUString& rClass )
1954 : SbxObject( rClass )
1955 {
1956 Initialize();
1957 }
1958
1959 BasicCollection::~BasicCollection()
1960 {}
1961
1962 void BasicCollection::Clear()
1963 {
1964 SbxObject::Clear();
1965 Initialize();
1966 }
1967
1968 void BasicCollection::Initialize()
1969 {
1970 xItemArray = new SbxArray();
1971 SetType( SbxOBJECT );
1972 SetFlag( SbxFlagBits::Fixed );
1973 ResetFlag( SbxFlagBits::Write );
1974 SbxVariable* p;
1975 p = Make( pCountStr, SbxClassType::Property, SbxINTEGER );
1976 p->ResetFlag( SbxFlagBits::Write );
1977 p->SetFlag( SbxFlagBits::DontStore );
1978 p = Make( pAddStr, SbxClassType::Method, SbxEMPTY );
1979 p->SetFlag( SbxFlagBits::DontStore );
1980 p = Make( pItemStr, SbxClassType::Method, SbxVARIANT );
1981 p->SetFlag( SbxFlagBits::DontStore );
1982 p = Make( pRemoveStr, SbxClassType::Method, SbxEMPTY );
1983 p->SetFlag( SbxFlagBits::DontStore );
1984 if ( !xAddInfo.is() )
1985 {
1986 xAddInfo = new SbxInfo;
1987 xAddInfo->AddParam( u"Item"_ustr, SbxVARIANT );
1988 xAddInfo->AddParam( u"Key"_ustr, SbxVARIANT, SbxFlagBits::Read | SbxFlagBits::Optional );
1989 xAddInfo->AddParam( u"Before"_ustr, SbxVARIANT, SbxFlagBits::Read | SbxFlagBits::Optional );
1990 xAddInfo->AddParam( u"After"_ustr, SbxVARIANT, SbxFlagBits::Read | SbxFlagBits::Optional );
1991 }
1992 if ( !xItemInfo.is() )
1993 {
1994 xItemInfo = new SbxInfo;
1995 xItemInfo->AddParam( u"Index"_ustr, SbxVARIANT, SbxFlagBits::Read | SbxFlagBits::Optional);
1996 }
1997 }
1998
1999 void BasicCollection::Notify( SfxBroadcaster& rCst, const SfxHint& rHint )
2000 {
2001 const SbxHint* p = dynamic_cast<const SbxHint*>(&rHint);
2002 if( p )
2003 {
2004 const SfxHintId nId = p->GetId();
2005 bool bRead = nId == SfxHintId::BasicDataWanted;
2006 bool bWrite = nId == SfxHintId::BasicDataChanged;
2007 bool bRequestInfo = nId == SfxHintId::BasicInfoWanted;
2008 SbxVariable* pVar = p->GetVar();
2009 SbxArray* pArg = pVar->GetParameters();
2010 OUString aVarName( pVar->GetName() );
2011 if( bRead || bWrite )
2012 {
2013 if( pVar->GetHashCode() == nCountHash
2014 && aVarName.equalsIgnoreAsciiCase( pCountStr ) )
2015 {
2016 pVar->PutLong(xItemArray->Count());
2017 }
2018 else if( pVar->GetHashCode() == nAddHash
2019 && aVarName.equalsIgnoreAsciiCase( pAddStr ) )
2020 {
2021 CollAdd( pArg );
2022 }
2023 else if( pVar->GetHashCode() == nItemHash
2024 && aVarName.equalsIgnoreAsciiCase( pItemStr ) )
2025 {
2026 CollItem( pArg );
2027 }
2028 else if( pVar->GetHashCode() == nRemoveHash
2029 && aVarName.equalsIgnoreAsciiCase( pRemoveStr ) )
2030 {
2031 CollRemove( pArg );
2032 }
2033 else
2034 {
2035 SbxObject::Notify( rCst, rHint );
2036 }
2037 return;
2038 }
2039 else if ( bRequestInfo )
2040 {
2041 if( pVar->GetHashCode() == nAddHash
2042 && aVarName.equalsIgnoreAsciiCase( pAddStr ) )
2043 {
2044 pVar->SetInfo( xAddInfo.get() );
2045 }
2046 else if( pVar->GetHashCode() == nItemHash
2047 && aVarName.equalsIgnoreAsciiCase( pItemStr ) )
2048 {
2049 pVar->SetInfo( xItemInfo.get() );
2050 }
2051 }
2052 }
2053 SbxObject::Notify( rCst, rHint );
2054 }
2055
2056 sal_Int32 BasicCollection::implGetIndex( SbxVariable const * pIndexVar )
2057 {
2058 sal_Int32 nIndex = -1;
2059 if( pIndexVar->GetType() == SbxSTRING )
2060 {
2061 nIndex = implGetIndexForName( pIndexVar->GetOUString() );
2062 }
2063 else
2064 {
2065 nIndex = pIndexVar->GetLong() - 1;
2066 }
2067 return nIndex;
2068 }
2069
2070 sal_Int32 BasicCollection::implGetIndexForName(const OUString& rName)
2071 {
2072 sal_Int32 nCount = xItemArray->Count();
2073 sal_Int32 nNameHash = MakeHashCode( rName );
2074
2075 // tdf#144245 - case-insensitive operation for non-ASCII characters
2076 OUString aNameCI; // Only initialize when matching hash found
2077
2078 for( sal_Int32 i = 0 ; i < nCount ; i++ )
2079 {
2080 SbxVariable* pVar = xItemArray->Get(i);
2081 if (pVar->GetHashCode() == nNameHash)
2082 {
2083 if (aNameCI.isEmpty() && !rName.isEmpty())
2084 aNameCI = SbxVariable::NameToCaseInsensitiveName(rName);
2085 if (aNameCI == pVar->GetName(SbxNameType::CaseInsensitive))
2086 return i;
2087 }
2088 }
2089 return -1;
2090 }
2091
2092 void BasicCollection::CollAdd( SbxArray* pPar_ )
2093 {
2094 sal_uInt32 nCount = pPar_->Count();
2095 if( nCount < 2 || nCount > 5 )
2096 {
2097 SetError( ERRCODE_BASIC_WRONG_ARGS );
2098 return;
2099 }
2100
2101 SbxVariable* pItem = pPar_->Get(1);
2102 if( pItem )
2103 {
2104 sal_uInt32 nNextIndex;
2105 if( nCount < 4 )
2106 {
2107 nNextIndex = xItemArray->Count();
2108 }
2109 else
2110 {
2111 SbxVariable* pBefore = pPar_->Get(3);
2112 if( nCount == 5 )
2113 {
2114 if( !( pBefore->IsErr() || ( pBefore->GetType() == SbxEMPTY ) ) )
2115 {
2116 SetError( ERRCODE_BASIC_BAD_ARGUMENT );
2117 return;
2118 }
2119 SbxVariable* pAfter = pPar_->Get(4);
2120 sal_Int32 nAfterIndex = implGetIndex( pAfter );
2121 if( nAfterIndex == -1 )
2122 {
2123 SetError( ERRCODE_BASIC_BAD_ARGUMENT );
2124 return;
2125 }
2126 nNextIndex = sal::static_int_cast<sal_uInt32>(nAfterIndex + 1);
2127 }
2128 else // if( nCount == 4 )
2129 {
2130 sal_Int32 nBeforeIndex = implGetIndex( pBefore );
2131 if( nBeforeIndex == -1 )
2132 {
2133 SetError( ERRCODE_BASIC_BAD_ARGUMENT );
2134 return;
2135 }
2136 nNextIndex = sal::static_int_cast<sal_uInt32>(nBeforeIndex);
2137 }
2138 }
2139
2140 auto pNewItem = tools::make_ref<SbxVariable>( *pItem );
2141 if( nCount >= 3 )
2142 {
2143 SbxVariable* pKey = pPar_->Get(2);
2144 if( !( pKey->IsErr() || ( pKey->GetType() == SbxEMPTY ) ) )
2145 {
2146 if( pKey->GetType() != SbxSTRING )
2147 {
2148 SetError( ERRCODE_BASIC_BAD_ARGUMENT );
2149 return;
2150 }
2151 OUString aKey = pKey->GetOUString();
2152 if( implGetIndexForName( aKey ) != -1 )
2153 {
2154 SetError( ERRCODE_BASIC_BAD_ARGUMENT );
2155 return;
2156 }
2157 pNewItem->SetName( aKey );
2158 }
2159 }
2160 pNewItem->SetFlag( SbxFlagBits::ReadWrite );
2161 xItemArray->Insert(pNewItem.get(), nNextIndex);
2162 }
2163 else
2164 {
2165 SetError( ERRCODE_BASIC_BAD_ARGUMENT );
2166 return;
2167 }
2168 }
2169
2170 void BasicCollection::CollItem( SbxArray* pPar_ )
2171 {
2172 if (pPar_->Count() != 2)
2173 {
2174 SetError( ERRCODE_BASIC_WRONG_ARGS );
2175 return;
2176 }
2177 SbxVariable* pRes = nullptr;
2178 SbxVariable* p = pPar_->Get(1);
2179 sal_Int32 nIndex = implGetIndex( p );
2180 if (nIndex >= 0 && o3tl::make_unsigned(nIndex) < xItemArray->Count())
2181 {
2182 pRes = xItemArray->Get(nIndex);
2183 }
2184 if( !pRes )
2185 {
2186 SetError( ERRCODE_BASIC_BAD_ARGUMENT );
2187 }
2188 else
2189 {
2190 *(pPar_->Get(0)) = *pRes;
2191 }
2192 }
2193
2194 void BasicCollection::CollRemove( SbxArray* pPar_ )
2195 {
2196 if (pPar_ == nullptr || pPar_->Count() != 2)
2197 {
2198 SetError( ERRCODE_BASIC_WRONG_ARGS );
2199 return;
2200 }
2201
2202 SbxVariable* p = pPar_->Get(1);
2203 sal_Int32 nIndex = implGetIndex( p );
2204 if (nIndex >= 0 && o3tl::make_unsigned(nIndex) < xItemArray->Count())
2205 {
2206 xItemArray->Remove( nIndex );
2207
2208 // Correct for stack if necessary
2209 SbiInstance* pInst = GetSbData()->pInst;
2210 SbiRuntime* pRT = pInst ? pInst->pRun : nullptr;
2211 if( pRT )
2212 {
2213 SbiForStack* pStack = pRT->FindForStackItemForCollection( this );
2214 if( pStack != nullptr )
2215 {
2216 if( pStack->nCurCollectionIndex >= nIndex )
2217 {
2218 --pStack->nCurCollectionIndex;
2219 }
2220 }
2221 }
2222 }
2223 else
2224 {
2225 SetError( ERRCODE_BASIC_BAD_ARGUMENT );
2226 }
2227 }
2228
2229 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */