LanguageTool: don't crash if REST protocol isn't set
[LibreOffice.git] / sc / source / filter / excel / xename.cxx
blob4bf336a16d09c72738babc6ed72b03f216243a46
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
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 <xename.hxx>
22 #include <map>
24 #include <document.hxx>
25 #include <rangenam.hxx>
26 #include <tokenarray.hxx>
27 #include <xehelper.hxx>
28 #include <xelink.hxx>
29 #include <excrecds.hxx>
30 #include <xlname.hxx>
31 #include <xeformula.hxx>
32 #include <xestring.hxx>
33 #include <xltools.hxx>
35 #include <formula/grammar.hxx>
36 #include <oox/export/utils.hxx>
37 #include <oox/token/tokens.hxx>
39 using namespace ::oox;
41 // *** Helper classes ***
43 namespace {
45 /** Represents an internal defined name, supports writing it to a NAME record. */
46 class XclExpName : public XclExpRecord, protected XclExpRoot
48 public:
49 /** Creates a standard defined name. */
50 explicit XclExpName( const XclExpRoot& rRoot, const OUString& rName );
51 /** Creates a built-in defined name. */
52 explicit XclExpName( const XclExpRoot& rRoot, sal_Unicode cBuiltIn );
54 /** Sets a token array containing the definition of this name. */
55 void SetTokenArray( const XclTokenArrayRef& xTokArr );
56 /** Changes this defined name to be local on the specified Calc sheet. */
57 void SetLocalTab( SCTAB nScTab );
58 /** Hides or unhides the defined name. */
59 void SetHidden( bool bHidden = true );
60 /** Changes this name to be the call to a VB macro function or procedure.
61 @param bVBasic true = Visual Basic macro, false = Sheet macro.
62 @param bFunc true = Macro function; false = Macro procedure. */
63 void SetMacroCall( bool bVBasic, bool bFunc );
65 /** Sets the name's symbol value
66 @param sValue the name's symbolic value */
67 void SetSymbol( const OUString& rValue );
69 /** Returns the original name (title) of this defined name. */
70 const OUString& GetOrigName() const { return maOrigName; }
71 /** Returns the Excel built-in name index of this defined name.
72 @return The built-in name index or EXC_BUILTIN_UNKNOWN for user-defined names. */
73 sal_Unicode GetBuiltInName() const { return mcBuiltIn; }
75 /** Returns the symbol value for this defined name. */
76 const OUString& GetSymbol() const { return msSymbol; }
78 /** Returns true, if this is a document-global defined name. */
79 bool IsGlobal() const { return mnXclTab == EXC_NAME_GLOBAL; }
80 /** Returns the Calc sheet of a local defined name. */
81 SCTAB GetScTab() const { return mnScTab; }
83 /** Returns true, if this defined name is volatile. */
84 bool IsVolatile() const;
85 /** Returns true, if this defined name describes a macro call.
86 @param bFunc true = Macro function; false = Macro procedure. */
87 bool IsMacroCall( bool bVBasic, bool bFunc ) const;
89 /** Writes the entire NAME record to the passed stream. */
90 virtual void Save( XclExpStream& rStrm ) override;
92 virtual void SaveXml( XclExpXmlStream& rStrm ) override;
94 private:
95 /** Writes the body of the NAME record to the passed stream. */
96 virtual void WriteBody( XclExpStream& rStrm ) override;
97 /** Convert localized range separators */
98 OUString GetWithDefaultRangeSeparator( const OUString& rSymbol ) const;
100 private:
101 OUString maOrigName; /// The original user-defined name.
102 OUString msSymbol; /// The value of the symbol
103 XclExpStringRef mxName; /// The name as Excel string object.
104 XclTokenArrayRef mxTokArr; /// The definition of the defined name.
105 sal_Unicode mcBuiltIn; /// The built-in index for built-in names.
106 SCTAB mnScTab; /// The Calc sheet index for local names.
107 sal_uInt16 mnFlags; /// Additional flags for this defined name.
108 sal_uInt16 mnExtSheet; /// The 1-based index to a global EXTERNSHEET record.
109 sal_uInt16 mnXclTab; /// The 1-based Excel sheet index for local names.
114 /** Implementation class of the name manager. */
115 class XclExpNameManagerImpl : protected XclExpRoot
117 public:
118 explicit XclExpNameManagerImpl( const XclExpRoot& rRoot );
120 /** Creates NAME records for built-in and user defined names. */
121 void Initialize();
123 /** Inserts the Calc name with the passed index and returns the Excel NAME index. */
124 sal_uInt16 InsertName( SCTAB nTab, sal_uInt16 nScNameIdx, SCTAB nCurrTab );
126 /** Inserts a new built-in defined name. */
127 sal_uInt16 InsertBuiltInName( sal_Unicode cBuiltIn, const XclTokenArrayRef& xTokArr, SCTAB nScTab, const ScRangeList& aRangeList );
128 sal_uInt16 InsertBuiltInName( sal_Unicode cBuiltIn, const XclTokenArrayRef& xTokArr, const ScRange& aRange );
129 /** Inserts a new defined name. Sets another unused name, if rName already exists. */
130 sal_uInt16 InsertUniqueName( const OUString& rName, const XclTokenArrayRef& xTokArr, SCTAB nScTab );
131 /** Returns index of an existing name, or creates a name without definition. */
132 sal_uInt16 InsertRawName( const OUString& rName );
133 /** Searches or inserts a defined name describing a macro name.
134 @param bVBasic true = Visual Basic macro; false = Sheet macro.
135 @param bFunc true = Macro function; false = Macro procedure. */
136 sal_uInt16 InsertMacroCall( const OUString& rMacroName, bool bVBasic, bool bFunc, bool bHidden );
138 /** Returns the NAME record at the specified position or 0 on error. */
139 const XclExpName* GetName( sal_uInt16 nNameIdx ) const;
141 /** Writes the entire list of NAME records.
142 @descr In BIFF7 and lower, writes the entire global link table, which
143 consists of an EXTERNCOUNT record, several EXTERNSHEET records, and
144 the list of NAME records. */
145 void Save( XclExpStream& rStrm );
147 void SaveXml( XclExpXmlStream& rStrm );
149 private:
150 typedef XclExpRecordList< XclExpName > XclExpNameList;
151 typedef XclExpNameList::RecordRefType XclExpNameRef;
153 typedef ::std::map< ::std::pair<SCTAB, OUString>, sal_uInt16> NamedExpMap;
155 private:
157 * @param nTab 0-based table index, or SCTAB_GLOBAL for global names.
158 * @param nScIdx calc's name index.
160 * @return excel's name index.
162 sal_uInt16 FindNamedExp( SCTAB nTab, OUString sName );
164 /** Returns the index of an existing built-in NAME record with the passed definition, otherwise 0. */
165 sal_uInt16 FindBuiltInNameIdx( const OUString& rName,
166 const OUString& sSymbol ) const;
167 /** Returns an unused name for the passed name. */
168 OUString GetUnusedName( const OUString& rName ) const;
170 /** Appends a new NAME record to the record list.
171 @return The 1-based NAME record index used elsewhere in the Excel file. */
172 sal_uInt16 Append( XclExpName* pName );
173 sal_uInt16 Append( XclExpNameRef const & rxName ) { return Append(rxName.get()); }
174 /** Creates a new NAME record for the passed user-defined name.
175 @return The 1-based NAME record index used elsewhere in the Excel file. */
176 sal_uInt16 CreateName( SCTAB nTab, const ScRangeData& rRangeData );
178 /** Creates NAME records for all built-in names in the document. */
179 void CreateBuiltInNames();
180 /** Creates NAME records for all user-defined names in the document. */
181 void CreateUserNames();
183 private:
185 * Maps Calc's named range to Excel's NAME records. Global names use
186 * -1 as their table index, whereas sheet-local names have 0-based table
187 * index.
189 NamedExpMap maNamedExpMap;
190 XclExpNameList maNameList; /// List of NAME records.
191 size_t mnFirstUserIdx; /// List index of first user-defined NAME record.
194 // *** Implementation ***
196 XclExpName::XclExpName( const XclExpRoot& rRoot, const OUString& rName ) :
197 XclExpRecord( EXC_ID_NAME ),
198 XclExpRoot( rRoot ),
199 maOrigName( rName ),
200 mxName( XclExpStringHelper::CreateString( rRoot, rName, XclStrFlags::EightBitLength ) ),
201 mcBuiltIn( EXC_BUILTIN_UNKNOWN ),
202 mnScTab( SCTAB_GLOBAL ),
203 mnFlags( EXC_NAME_DEFAULT ),
204 mnExtSheet( EXC_NAME_GLOBAL ),
205 mnXclTab( EXC_NAME_GLOBAL )
209 XclExpName::XclExpName( const XclExpRoot& rRoot, sal_Unicode cBuiltIn ) :
210 XclExpRecord( EXC_ID_NAME ),
211 XclExpRoot( rRoot ),
212 mcBuiltIn( cBuiltIn ),
213 mnScTab( SCTAB_GLOBAL ),
214 mnFlags( EXC_NAME_DEFAULT ),
215 mnExtSheet( EXC_NAME_GLOBAL ),
216 mnXclTab( EXC_NAME_GLOBAL )
218 // filter source range is hidden in Excel
219 if( cBuiltIn == EXC_BUILTIN_FILTERDATABASE )
220 SetHidden();
222 // special case for BIFF5/7 filter source range - name appears as plain text without built-in flag
223 if( (GetBiff() <= EXC_BIFF5) && (cBuiltIn == EXC_BUILTIN_FILTERDATABASE) )
225 OUString aName( XclTools::GetXclBuiltInDefName( EXC_BUILTIN_FILTERDATABASE ) );
226 mxName = XclExpStringHelper::CreateString( rRoot, aName, XclStrFlags::EightBitLength );
227 maOrigName = XclTools::GetXclBuiltInDefName( cBuiltIn );
229 else
231 maOrigName = XclTools::GetBuiltInDefNameXml( cBuiltIn ) ;
232 mxName = XclExpStringHelper::CreateString( rRoot, cBuiltIn, XclStrFlags::EightBitLength );
233 ::set_flag( mnFlags, EXC_NAME_BUILTIN );
237 void XclExpName::SetTokenArray( const XclTokenArrayRef& xTokArr )
239 mxTokArr = xTokArr;
242 void XclExpName::SetLocalTab( SCTAB nScTab )
244 OSL_ENSURE( GetTabInfo().IsExportTab( nScTab ), "XclExpName::SetLocalTab - invalid sheet index" );
245 if( !GetTabInfo().IsExportTab( nScTab ) )
246 return;
248 mnScTab = nScTab;
249 GetGlobalLinkManager().FindExtSheet( mnExtSheet, mnXclTab, nScTab );
251 // special handling for NAME record
252 switch( GetBiff() )
254 case EXC_BIFF5: // EXTERNSHEET index is positive in NAME record
255 mnExtSheet = ~mnExtSheet + 1;
256 break;
257 case EXC_BIFF8: // EXTERNSHEET index not used, but must be created in link table
258 mnExtSheet = 0;
259 break;
260 default: DBG_ERROR_BIFF();
263 // Excel sheet index is 1-based
264 ++mnXclTab;
267 void XclExpName::SetHidden( bool bHidden )
269 ::set_flag( mnFlags, EXC_NAME_HIDDEN, bHidden );
272 void XclExpName::SetMacroCall( bool bVBasic, bool bFunc )
274 ::set_flag( mnFlags, EXC_NAME_PROC );
275 ::set_flag( mnFlags, EXC_NAME_VB, bVBasic );
276 ::set_flag( mnFlags, EXC_NAME_FUNC, bFunc );
279 void XclExpName::SetSymbol( const OUString& rSymbol )
281 msSymbol = rSymbol;
284 bool XclExpName::IsVolatile() const
286 return mxTokArr && mxTokArr->IsVolatile();
289 bool XclExpName::IsMacroCall( bool bVBasic, bool bFunc ) const
291 return
292 (::get_flag( mnFlags, EXC_NAME_VB ) == bVBasic) &&
293 (::get_flag( mnFlags, EXC_NAME_FUNC ) == bFunc);
296 void XclExpName::Save( XclExpStream& rStrm )
298 OSL_ENSURE( mxName && (mxName->Len() > 0), "XclExpName::Save - missing name" );
299 OSL_ENSURE( !(IsGlobal() && ::get_flag( mnFlags, EXC_NAME_BUILTIN )), "XclExpName::Save - global built-in name" );
300 SetRecSize( 11 + mxName->GetSize() + (mxTokArr ? mxTokArr->GetSize() : 2) );
301 XclExpRecord::Save( rStrm );
304 OUString XclExpName::GetWithDefaultRangeSeparator( const OUString& rSymbol ) const
306 sal_Int32 nPos = rSymbol.indexOf(';');
307 if ( nPos > -1 )
309 // convert with validation
310 ScRange aRange;
311 ScAddress::Details detailsXL( ::formula::FormulaGrammar::CONV_XL_A1 );
312 ScRefFlags nRes = aRange.Parse( rSymbol.copy(0, nPos), GetDoc(), detailsXL );
313 if ( nRes & ScRefFlags::VALID )
315 nRes = aRange.Parse( rSymbol.copy(nPos+1), GetDoc(), detailsXL );
316 if ( nRes & ScRefFlags::VALID )
318 return rSymbol.replaceFirst(";", ",");
322 return rSymbol;
325 void XclExpName::SaveXml( XclExpXmlStream& rStrm )
327 sax_fastparser::FSHelperPtr& rWorkbook = rStrm.GetCurrentStream();
328 rWorkbook->startElement( XML_definedName,
329 // OOXTODO: XML_comment, "",
330 // OOXTODO: XML_customMenu, "",
331 // OOXTODO: XML_description, "",
332 XML_function, ToPsz( ::get_flag( mnFlags, EXC_NAME_VB ) ),
333 // OOXTODO: XML_functionGroupId, "",
334 // OOXTODO: XML_help, "",
335 XML_hidden, ToPsz( ::get_flag( mnFlags, EXC_NAME_HIDDEN ) ),
336 XML_localSheetId, mnScTab == SCTAB_GLOBAL ? nullptr : OString::number( mnScTab ).getStr(),
337 XML_name, maOrigName.toUtf8(),
338 // OOXTODO: XML_publishToServer, "",
339 // OOXTODO: XML_shortcutKey, "",
340 // OOXTODO: XML_statusBar, "",
341 XML_vbProcedure, ToPsz( ::get_flag( mnFlags, EXC_NAME_VB ) )
342 // OOXTODO: XML_workbookParameter, "",
343 // OOXTODO: XML_xlm, ""
345 rWorkbook->writeEscaped( GetWithDefaultRangeSeparator( msSymbol ) );
346 rWorkbook->endElement( XML_definedName );
349 void XclExpName::WriteBody( XclExpStream& rStrm )
351 sal_uInt16 nFmlaSize = mxTokArr ? mxTokArr->GetSize() : 0;
353 rStrm << mnFlags // flags
354 << sal_uInt8( 0 ); // keyboard shortcut
355 mxName->WriteLenField( rStrm ); // length of name
356 rStrm << nFmlaSize // size of token array
357 << mnExtSheet // BIFF5/7: EXTSHEET index, BIFF8: not used
358 << mnXclTab // 1-based sheet index for local names
359 << sal_uInt32( 0 ); // length of menu/descr/help/status text
360 mxName->WriteFlagField( rStrm ); // BIFF8 flag field (no-op in <=BIFF7)
361 mxName->WriteBuffer( rStrm ); // character array of the name
362 if( mxTokArr )
363 mxTokArr->WriteArray( rStrm ); // token array without size
366 /** Returns true (needed fixing) if FormulaToken was not absolute and 3D.
367 So, regardless of whether the fix was successful or not, true is still returned since a fix was required.*/
368 static bool lcl_EnsureAbs3DToken( const SCTAB nTab, formula::FormulaToken* pTok, const bool bFix = true )
370 bool bFixRequired = false;
371 if ( !pTok || ( pTok->GetType() != formula::svSingleRef && pTok->GetType() != formula::svDoubleRef ) )
372 return bFixRequired;
374 ScSingleRefData* pRef1 = pTok->GetSingleRef();
375 if ( !pRef1 )
376 return bFixRequired;
378 ScSingleRefData* pRef2 = nullptr;
379 if ( pTok->GetType() == formula::svDoubleRef )
380 pRef2 = pTok->GetSingleRef2();
382 if ( pRef1->IsTabRel() || !pRef1->IsFlag3D() )
384 bFixRequired = true;
385 if ( bFix )
387 if ( pRef1->IsTabRel() && nTab != SCTAB_GLOBAL )
388 pRef1->SetAbsTab( nTab + pRef1->Tab() ); //XLS requirement
389 if ( !pRef1->IsTabRel() )
391 pRef1->SetFlag3D( true ); //XLSX requirement
392 if ( pRef2 && !pRef2->IsTabRel() )
393 pRef2->SetFlag3D( pRef2->Tab() != pRef1->Tab() );
398 if ( pRef2 && pRef2->IsTabRel() && !pRef1->IsTabRel() )
400 bFixRequired = true;
401 if ( bFix && nTab != SCTAB_GLOBAL )
403 pRef2->SetAbsTab( nTab + pRef2->Tab() );
404 pRef2->SetFlag3D( pRef2->Tab() != pRef1->Tab() );
407 return bFixRequired;
410 XclExpNameManagerImpl::XclExpNameManagerImpl( const XclExpRoot& rRoot ) :
411 XclExpRoot( rRoot ),
412 mnFirstUserIdx( 0 )
416 void XclExpNameManagerImpl::Initialize()
418 CreateBuiltInNames();
419 mnFirstUserIdx = maNameList.GetSize();
420 CreateUserNames();
423 sal_uInt16 XclExpNameManagerImpl::InsertName( SCTAB nTab, sal_uInt16 nScNameIdx, SCTAB nCurrTab )
425 sal_uInt16 nNameIdx = 0;
426 const ScRangeData* pData = nullptr;
427 ScRangeName* pRN = (nTab == SCTAB_GLOBAL) ? GetDoc().GetRangeName() : GetDoc().GetRangeName(nTab);
428 if (pRN)
429 pData = pRN->findByIndex(nScNameIdx);
431 if (pData)
433 bool bEmulateGlobalRelativeTable = false;
434 const ScTokenArray* pCode = pData->GetCode();
435 if ( pCode
436 && nTab == SCTAB_GLOBAL
437 && (pData->HasType( ScRangeData::Type::AbsPos ) || pData->HasType( ScRangeData::Type::AbsArea )) )
439 bEmulateGlobalRelativeTable = lcl_EnsureAbs3DToken( nTab, pCode->FirstToken(), /*bFix=*/false );
441 nNameIdx = FindNamedExp( bEmulateGlobalRelativeTable ? nCurrTab : nTab, pData->GetName() );
442 if (!nNameIdx)
443 nNameIdx = CreateName(nTab, *pData);
446 return nNameIdx;
449 sal_uInt16 XclExpNameManagerImpl::InsertBuiltInName( sal_Unicode cBuiltIn, const XclTokenArrayRef& xTokArr, const ScRange& aRange )
451 XclExpNameRef xName = new XclExpName( GetRoot(), cBuiltIn );
452 xName->SetTokenArray( xTokArr );
453 xName->SetLocalTab( aRange.aStart.Tab() );
454 OUString sSymbol(aRange.Format(GetDoc(), ScRefFlags::RANGE_ABS_3D, ScAddress::Details( ::formula::FormulaGrammar::CONV_XL_A1)));
455 xName->SetSymbol( sSymbol );
456 return Append( xName );
459 sal_uInt16 XclExpNameManagerImpl::InsertBuiltInName( sal_Unicode cBuiltIn, const XclTokenArrayRef& xTokArr, SCTAB nScTab, const ScRangeList& rRangeList )
461 XclExpNameRef xName = new XclExpName( GetRoot(), cBuiltIn );
462 xName->SetTokenArray( xTokArr );
463 xName->SetLocalTab( nScTab );
464 OUString sSymbol;
465 rRangeList.Format( sSymbol, ScRefFlags::RANGE_ABS_3D, GetDoc(), ::formula::FormulaGrammar::CONV_XL_A1 );
466 xName->SetSymbol( sSymbol );
467 return Append( xName );
470 sal_uInt16 XclExpNameManagerImpl::InsertUniqueName(
471 const OUString& rName, const XclTokenArrayRef& xTokArr, SCTAB nScTab )
473 OSL_ENSURE( !rName.isEmpty(), "XclExpNameManagerImpl::InsertUniqueName - empty name" );
474 XclExpNameRef xName = new XclExpName( GetRoot(), GetUnusedName( rName ) );
475 xName->SetTokenArray( xTokArr );
476 xName->SetLocalTab( nScTab );
477 return Append( xName );
480 sal_uInt16 XclExpNameManagerImpl::InsertRawName( const OUString& rName )
482 // empty name? may occur in broken external Calc tokens
483 if( rName.isEmpty() )
484 return 0;
486 // try to find an existing NAME record, regardless of its type
487 for( size_t nListIdx = mnFirstUserIdx, nListSize = maNameList.GetSize(); nListIdx < nListSize; ++nListIdx )
489 XclExpNameRef xName = maNameList.GetRecord( nListIdx );
490 if( xName->IsGlobal() && (xName->GetOrigName() == rName) )
491 return static_cast< sal_uInt16 >( nListIdx + 1 );
494 // create a new NAME record
495 XclExpNameRef xName = new XclExpName( GetRoot(), rName );
496 return Append( xName );
499 sal_uInt16 XclExpNameManagerImpl::InsertMacroCall( const OUString& rMacroName, bool bVBasic, bool bFunc, bool bHidden )
501 // empty name? may occur in broken external Calc tokens
502 if( rMacroName.isEmpty() )
503 return 0;
505 // try to find an existing NAME record
506 for( size_t nListIdx = mnFirstUserIdx, nListSize = maNameList.GetSize(); nListIdx < nListSize; ++nListIdx )
508 XclExpNameRef xName = maNameList.GetRecord( nListIdx );
509 if( xName->IsMacroCall( bVBasic, bFunc ) && (xName->GetOrigName() == rMacroName) )
510 return static_cast< sal_uInt16 >( nListIdx + 1 );
513 // create a new NAME record
514 XclExpNameRef xName = new XclExpName( GetRoot(), rMacroName );
515 xName->SetMacroCall( bVBasic, bFunc );
516 xName->SetHidden( bHidden );
518 // for sheet macros, add a #NAME! error
519 if( !bVBasic )
520 xName->SetTokenArray( GetFormulaCompiler().CreateErrorFormula( EXC_ERR_NAME ) );
522 return Append( xName );
525 const XclExpName* XclExpNameManagerImpl::GetName( sal_uInt16 nNameIdx ) const
527 OSL_ENSURE( maNameList.HasRecord( nNameIdx - 1 ), "XclExpNameManagerImpl::GetName - wrong record index" );
528 return maNameList.GetRecord( nNameIdx - 1 );
531 void XclExpNameManagerImpl::Save( XclExpStream& rStrm )
533 maNameList.Save( rStrm );
536 void XclExpNameManagerImpl::SaveXml( XclExpXmlStream& rStrm )
538 if( maNameList.IsEmpty() )
539 return;
540 sax_fastparser::FSHelperPtr& rWorkbook = rStrm.GetCurrentStream();
541 rWorkbook->startElement(XML_definedNames);
542 maNameList.SaveXml( rStrm );
543 rWorkbook->endElement( XML_definedNames );
546 // private --------------------------------------------------------------------
548 sal_uInt16 XclExpNameManagerImpl::FindNamedExp( SCTAB nTab, OUString sName )
550 NamedExpMap::key_type key(nTab, sName);
551 NamedExpMap::const_iterator itr = maNamedExpMap.find(key);
552 return (itr == maNamedExpMap.end()) ? 0 : itr->second;
555 sal_uInt16 XclExpNameManagerImpl::FindBuiltInNameIdx(
556 const OUString& rName, const OUString& sSymbol ) const
558 /* Get built-in index from the name. Special case: the database range
559 'unnamed' will be mapped to Excel's built-in '_FilterDatabase' name. */
560 sal_Unicode cBuiltIn = XclTools::GetBuiltInDefNameIndex( rName );
562 if( cBuiltIn < EXC_BUILTIN_UNKNOWN )
564 // try to find the record in existing built-in NAME record list
565 for( size_t nPos = 0; nPos < mnFirstUserIdx; ++nPos )
567 XclExpNameRef xName = maNameList.GetRecord( nPos );
568 if( xName->GetBuiltInName() == cBuiltIn && xName->GetSymbol().replace(';', ',') == sSymbol.replace(';', ',') )
570 // tdf#112567 restore the original built-in names with non-localized separators
571 // TODO: support more localizations, if needed
572 if ( xName->GetSymbol() != sSymbol )
574 xName->SetSymbol(xName->GetSymbol().replace(';', ','));
576 return static_cast< sal_uInt16 >( nPos + 1 );
580 return 0;
583 OUString XclExpNameManagerImpl::GetUnusedName( const OUString& rName ) const
585 OUString aNewName( rName );
586 sal_Int32 nAppIdx = 0;
587 bool bExist = true;
588 while( bExist )
590 // search the list of user-defined names
591 bExist = false;
592 for( size_t nPos = mnFirstUserIdx, nSize = maNameList.GetSize(); !bExist && (nPos < nSize); ++nPos )
594 XclExpNameRef xName = maNameList.GetRecord( nPos );
595 bExist = xName->GetOrigName() == aNewName;
596 // name exists -> create a new name "<originalname>_<counter>"
597 if( bExist )
598 aNewName = rName + "_" + OUString::number( ++nAppIdx );
601 return aNewName;
604 sal_uInt16 XclExpNameManagerImpl::Append( XclExpName* pName )
606 if( maNameList.GetSize() == 0xFFFF )
607 return 0;
608 maNameList.AppendRecord( pName );
609 return static_cast< sal_uInt16 >( maNameList.GetSize() ); // 1-based
612 sal_uInt16 XclExpNameManagerImpl::CreateName( SCTAB nTab, const ScRangeData& rRangeData )
614 const OUString& rName = rRangeData.GetName();
616 /* #i38821# recursive names: first insert the (empty) name object,
617 otherwise a recursive call of this function from the formula compiler
618 with the same defined name will not find it and will create it again. */
619 size_t nOldListSize = maNameList.GetSize();
620 XclExpNameRef xName = new XclExpName( GetRoot(), rName );
621 if (nTab != SCTAB_GLOBAL)
622 xName->SetLocalTab(nTab);
623 sal_uInt16 nNameIdx = Append( xName );
624 // store the index of the NAME record in the lookup map
625 NamedExpMap::key_type key(nTab, rRangeData.GetName());
626 maNamedExpMap[key] = nNameIdx;
628 /* Create the definition formula.
629 This may cause recursive creation of other defined names. */
630 if( const ScTokenArray* pScTokArr = const_cast< ScRangeData& >( rRangeData ).GetCode() )
632 XclTokenArrayRef xTokArr;
633 OUString sSymbol;
634 // MSO requires named ranges to have absolute sheet references
635 if ( rRangeData.HasType( ScRangeData::Type::AbsPos ) || rRangeData.HasType( ScRangeData::Type::AbsArea ) )
637 // Don't modify the actual document; use a temporary copy to create the export formulas.
638 std::unique_ptr<ScTokenArray> pTokenCopy( pScTokArr->Clone() );
639 lcl_EnsureAbs3DToken(nTab, pTokenCopy->FirstToken());
641 xTokArr = GetFormulaCompiler().CreateFormula(EXC_FMLATYPE_NAME, *pTokenCopy);
642 if ( GetOutput() != EXC_OUTPUT_BINARY )
644 ScCompiler aComp(GetDoc(), rRangeData.GetPos(), *pTokenCopy,
645 formula::FormulaGrammar::GRAM_OOXML);
646 aComp.CreateStringFromTokenArray( sSymbol );
649 else
651 bool bOOXML = GetOutput() == EXC_OUTPUT_XML_2007;
652 xTokArr = GetFormulaCompiler().CreateFormula( EXC_FMLATYPE_NAME, *pScTokArr, bOOXML ?
653 &rRangeData.GetPos() : nullptr );
654 sSymbol = rRangeData.GetSymbol( (GetOutput() == EXC_OUTPUT_BINARY) ?
655 formula::FormulaGrammar::GRAM_ENGLISH_XL_A1 : formula::FormulaGrammar::GRAM_OOXML);
657 xName->SetTokenArray( xTokArr );
658 xName->SetSymbol( sSymbol );
660 /* Try to replace by existing built-in name - complete token array is
661 needed for comparison, and due to the recursion problem above this
662 cannot be done earlier. If a built-in name is found, the created NAME
663 record for this name and all following records in the list must be
664 deleted, otherwise they may contain wrong name list indexes. */
665 sal_uInt16 nBuiltInIdx = FindBuiltInNameIdx( rName, sSymbol );
666 if( nBuiltInIdx != 0 )
668 // delete the new NAME records
669 while( maNameList.GetSize() > nOldListSize )
670 maNameList.RemoveRecord( maNameList.GetSize() - 1 );
671 // use index of the found built-in NAME record
672 key = NamedExpMap::key_type(nTab, rRangeData.GetName());
673 maNamedExpMap[key] = nNameIdx = nBuiltInIdx;
677 return nNameIdx;
680 void XclExpNameManagerImpl::CreateBuiltInNames()
682 ScDocument& rDoc = GetDoc();
683 XclExpTabInfo& rTabInfo = GetTabInfo();
685 /* #i2394# built-in defined names must be sorted by the name of the
686 containing sheet. Example: SheetA!Print_Range must be stored *before*
687 SheetB!Print_Range, regardless of the position of SheetA in the document! */
688 for( SCTAB nScTabIdx = 0, nScTabCount = rTabInfo.GetScTabCount(); nScTabIdx < nScTabCount; ++nScTabIdx )
690 // find real sheet index from the nScTabIdx counter
691 SCTAB nScTab = rTabInfo.GetRealScTab( nScTabIdx );
692 // create NAME records for all built-in names of this sheet
693 if( rTabInfo.IsExportTab( nScTab ) )
695 // *** 1) print ranges *** ----------------------------------------
697 if( rDoc.HasPrintRange() )
699 ScRangeList aRangeList;
700 for( sal_uInt16 nIdx = 0, nCount = rDoc.GetPrintRangeCount( nScTab ); nIdx < nCount; ++nIdx )
702 const ScRange* pPrintRange = rDoc.GetPrintRange( nScTab, nIdx );
703 if (!pPrintRange)
704 continue;
705 ScRange aRange( *pPrintRange );
706 // Calc document does not care about sheet index in print ranges
707 aRange.aStart.SetTab( nScTab );
708 aRange.aEnd.SetTab( nScTab );
709 aRange.PutInOrder();
710 aRangeList.push_back( aRange );
712 // create the NAME record (do not warn if ranges are shrunken)
713 GetAddressConverter().ValidateRangeList( aRangeList, false );
714 if( !aRangeList.empty() )
715 GetNameManager().InsertBuiltInName( EXC_BUILTIN_PRINTAREA, aRangeList );
718 // *** 2) print titles *** ----------------------------------------
720 ScRangeList aTitleList;
721 // repeated columns
722 if( const ScRange* pColRange = rDoc.GetRepeatColRange( nScTab ) )
723 aTitleList.push_back( ScRange(
724 pColRange->aStart.Col(), 0, nScTab,
725 pColRange->aEnd.Col(), GetXclMaxPos().Row(), nScTab ) );
726 // repeated rows
727 if( const ScRange* pRowRange = rDoc.GetRepeatRowRange( nScTab ) )
728 aTitleList.push_back( ScRange(
729 0, pRowRange->aStart.Row(), nScTab,
730 GetXclMaxPos().Col(), pRowRange->aEnd.Row(), nScTab ) );
731 // create the NAME record
732 GetAddressConverter().ValidateRangeList( aTitleList, false );
733 if( !aTitleList.empty() )
734 GetNameManager().InsertBuiltInName( EXC_BUILTIN_PRINTTITLES, aTitleList );
736 // *** 3) filter ranges *** ---------------------------------------
738 if( GetBiff() == EXC_BIFF8 )
739 GetFilterManager().InitTabFilter( nScTab );
744 void XclExpNameManagerImpl::CreateUserNames()
746 std::vector<ScRangeData*> vEmulateAsLocalRange;
747 const ScRangeName& rNamedRanges = GetNamedRanges();
748 for (const auto& rEntry : rNamedRanges)
750 // skip definitions of shared formulas
751 if (!FindNamedExp(SCTAB_GLOBAL, rEntry.second->GetName()))
753 const ScTokenArray* pCode = rEntry.second->GetCode();
754 if ( pCode
755 && (rEntry.second->HasType( ScRangeData::Type::AbsPos ) || rEntry.second->HasType( ScRangeData::Type::AbsArea ))
756 && lcl_EnsureAbs3DToken( SCTAB_GLOBAL, pCode->FirstToken(), /*bFix=*/false ) )
758 vEmulateAsLocalRange.emplace_back(rEntry.second.get());
760 else
761 CreateName(SCTAB_GLOBAL, *rEntry.second);
764 //look at sheets containing local range names
765 ScRangeName::TabNameCopyMap rLocalNames;
766 GetDoc().GetAllTabRangeNames(rLocalNames);
767 for (const auto& [rTab, pRangeName] : rLocalNames)
769 for (const auto& rEntry : *pRangeName)
771 // skip definitions of shared formulas
772 if (!FindNamedExp(rTab, rEntry.second->GetName()))
773 CreateName(rTab, *rEntry.second);
777 // Emulate relative global variables by creating a copy in each local range.
778 // Creating AFTER true local range names so that conflicting global names will be ignored.
779 for ( SCTAB nTab = 0; nTab < GetDoc().GetTableCount(); ++nTab )
781 for ( auto rangeDataItr : vEmulateAsLocalRange )
783 if ( !FindNamedExp(nTab, rangeDataItr->GetName()) )
784 CreateName(nTab, *rangeDataItr );
789 XclExpNameManager::XclExpNameManager( const XclExpRoot& rRoot ) :
790 XclExpRoot( rRoot ),
791 mxImpl( std::make_shared<XclExpNameManagerImpl>( rRoot ) )
795 XclExpNameManager::~XclExpNameManager()
799 void XclExpNameManager::Initialize()
801 mxImpl->Initialize();
804 sal_uInt16 XclExpNameManager::InsertName( SCTAB nTab, sal_uInt16 nScNameIdx, SCTAB nCurrTab )
806 return mxImpl->InsertName( nTab, nScNameIdx, nCurrTab );
809 sal_uInt16 XclExpNameManager::InsertBuiltInName( sal_Unicode cBuiltIn, const ScRange& rRange )
811 XclTokenArrayRef xTokArr = GetFormulaCompiler().CreateFormula( EXC_FMLATYPE_NAME, rRange );
812 return mxImpl->InsertBuiltInName( cBuiltIn, xTokArr, rRange );
815 sal_uInt16 XclExpNameManager::InsertBuiltInName( sal_Unicode cBuiltIn, const ScRangeList& rRangeList )
817 sal_uInt16 nNameIdx = 0;
818 if( !rRangeList.empty() )
820 XclTokenArrayRef xTokArr = GetFormulaCompiler().CreateFormula( EXC_FMLATYPE_NAME, rRangeList );
821 nNameIdx = mxImpl->InsertBuiltInName( cBuiltIn, xTokArr, rRangeList.front().aStart.Tab(), rRangeList );
823 return nNameIdx;
826 sal_uInt16 XclExpNameManager::InsertUniqueName(
827 const OUString& rName, const XclTokenArrayRef& xTokArr, SCTAB nScTab )
829 return mxImpl->InsertUniqueName( rName, xTokArr, nScTab );
832 sal_uInt16 XclExpNameManager::InsertRawName( const OUString& rName )
834 return mxImpl->InsertRawName( rName );
837 sal_uInt16 XclExpNameManager::InsertMacroCall( const OUString& rMacroName, bool bVBasic, bool bFunc, bool bHidden )
839 return mxImpl->InsertMacroCall( rMacroName, bVBasic, bFunc, bHidden );
842 OUString XclExpNameManager::GetOrigName( sal_uInt16 nNameIdx ) const
844 const XclExpName* pName = mxImpl->GetName( nNameIdx );
845 return pName ? pName->GetOrigName() : OUString();
848 SCTAB XclExpNameManager::GetScTab( sal_uInt16 nNameIdx ) const
850 const XclExpName* pName = mxImpl->GetName( nNameIdx );
851 return pName ? pName->GetScTab() : SCTAB_GLOBAL;
854 bool XclExpNameManager::IsVolatile( sal_uInt16 nNameIdx ) const
856 const XclExpName* pName = mxImpl->GetName( nNameIdx );
857 return pName && pName->IsVolatile();
860 void XclExpNameManager::Save( XclExpStream& rStrm )
862 mxImpl->Save( rStrm );
865 void XclExpNameManager::SaveXml( XclExpXmlStream& rStrm )
867 mxImpl->SaveXml( rStrm );
870 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */