fix baseline build (old cairo) - 'cairo_rectangle_int_t' does not name a type
[LibreOffice.git] / sc / source / ui / unoobj / funcuno.cxx
blob00d9e7951984fa9f8f6c602892bf630173e5e7ad
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 <cppuhelper/supportsservice.hxx>
21 #include <sfx2/app.hxx>
22 #include <svl/itemprop.hxx>
23 #include <svl/sharedstringpool.hxx>
25 #include "scitems.hxx"
26 #include "funcuno.hxx"
27 #include "miscuno.hxx"
28 #include "cellsuno.hxx"
29 #include "scdll.hxx"
30 #include "document.hxx"
31 #include "compiler.hxx"
32 #include <formula/errorcodes.hxx>
33 #include "callform.hxx"
34 #include "addincol.hxx"
35 #include "rangeseq.hxx"
36 #include "formulacell.hxx"
37 #include "docoptio.hxx"
38 #include "optuno.hxx"
39 #include <docuno.hxx>
40 #include "markdata.hxx"
41 #include "patattr.hxx"
42 #include "docpool.hxx"
43 #include "attrib.hxx"
44 #include "clipparam.hxx"
45 #include "dociter.hxx"
46 #include "stringutil.hxx"
47 #include "tokenarray.hxx"
49 using namespace com::sun::star;
51 // registered as implementation for service FunctionAccess,
52 // also supports service SpreadsheetDocumentSettings (to set null date etc.)
54 #define SCFUNCTIONACCESS_SERVICE "com.sun.star.sheet.FunctionAccess"
55 #define SCDOCSETTINGS_SERVICE "com.sun.star.sheet.SpreadsheetDocumentSettings"
57 // helper to use cached document if not in use, temporary document otherwise
59 class ScTempDocSource
61 private:
62 ScTempDocCache& rCache;
63 ScDocument* pTempDoc;
65 static ScDocument* CreateDocument(); // create and initialize doc
67 public:
68 ScTempDocSource( ScTempDocCache& rDocCache );
69 ~ScTempDocSource();
71 ScDocument* GetDocument();
74 ScDocument* ScTempDocSource::CreateDocument()
76 ScDocument* pDoc = new ScDocument; // SCDOCMODE_DOCUMENT
77 pDoc->MakeTable( 0 );
78 return pDoc;
81 ScTempDocSource::ScTempDocSource( ScTempDocCache& rDocCache ) :
82 rCache( rDocCache ),
83 pTempDoc( NULL )
85 if ( rCache.IsInUse() )
86 pTempDoc = CreateDocument();
87 else
89 rCache.SetInUse( true );
90 if ( !rCache.GetDocument() )
91 rCache.SetDocument( CreateDocument() );
95 ScTempDocSource::~ScTempDocSource()
97 if ( pTempDoc )
98 delete pTempDoc;
99 else
100 rCache.SetInUse( false );
103 ScDocument* ScTempDocSource::GetDocument()
105 if ( pTempDoc )
106 return pTempDoc;
107 else
108 return rCache.GetDocument();
111 ScTempDocCache::ScTempDocCache() :
112 pDoc( NULL ),
113 bInUse( false )
117 ScTempDocCache::~ScTempDocCache()
119 OSL_ENSURE( !bInUse, "ScTempDocCache dtor: bInUse" );
120 delete pDoc;
123 void ScTempDocCache::SetDocument( ScDocument* pNew )
125 OSL_ENSURE( !pDoc, "ScTempDocCache::SetDocument: already set" );
126 pDoc = pNew;
129 void ScTempDocCache::Clear()
131 OSL_ENSURE( !bInUse, "ScTempDocCache::Clear: bInUse" );
132 delete pDoc;
133 pDoc = NULL;
136 // copy results from one document into another
137 //! merge this with ScAreaLink::Refresh
138 //! copy directly without a clipboard document?
140 static bool lcl_CopyData( ScDocument* pSrcDoc, const ScRange& rSrcRange,
141 ScDocument* pDestDoc, const ScAddress& rDestPos )
143 SCTAB nSrcTab = rSrcRange.aStart.Tab();
144 SCTAB nDestTab = rDestPos.Tab();
146 ScRange aNewRange( rDestPos, ScAddress(
147 rSrcRange.aEnd.Col() - rSrcRange.aStart.Col() + rDestPos.Col(),
148 rSrcRange.aEnd.Row() - rSrcRange.aStart.Row() + rDestPos.Row(),
149 nDestTab ) );
151 ScDocument* pClipDoc = new ScDocument( SCDOCMODE_CLIP );
152 ScMarkData aSourceMark;
153 aSourceMark.SelectOneTable( nSrcTab ); // for CopyToClip
154 aSourceMark.SetMarkArea( rSrcRange );
155 ScClipParam aClipParam(rSrcRange, false);
156 pSrcDoc->CopyToClip(aClipParam, pClipDoc, &aSourceMark, false);
158 if ( pClipDoc->HasAttrib( 0,0,nSrcTab, MAXCOL,MAXROW,nSrcTab,
159 HASATTR_MERGED | HASATTR_OVERLAPPED ) )
161 ScPatternAttr aPattern( pSrcDoc->GetPool() );
162 aPattern.GetItemSet().Put( ScMergeAttr() ); // Defaults
163 aPattern.GetItemSet().Put( ScMergeFlagAttr() );
164 pClipDoc->ApplyPatternAreaTab( 0,0, MAXCOL,MAXROW, nSrcTab, aPattern );
167 ScMarkData aDestMark;
168 aDestMark.SelectOneTable( nDestTab );
169 aDestMark.SetMarkArea( aNewRange );
170 pDestDoc->CopyFromClip( aNewRange, aDestMark, IDF_ALL & ~IDF_FORMULA, NULL, pClipDoc, false );
172 delete pClipDoc;
173 return true;
176 ScFunctionAccess::ScFunctionAccess() :
177 pOptions( NULL ),
178 aPropertyMap( ScDocOptionsHelper::GetPropertyMap() ),
179 mbArray( true ), // default according to behaviour of older Office versions
180 mbValid( true )
182 StartListening( *SfxGetpApp() ); // for SFX_HINT_DEINITIALIZING
185 ScFunctionAccess::~ScFunctionAccess()
187 delete pOptions;
189 // SfxBroadcaster::RemoveListener checks DBG_TESTSOLARMUTEX():
190 SolarMutexGuard g;
191 EndListeningAll();
195 void ScFunctionAccess::Notify( SfxBroadcaster&, const SfxHint& rHint )
197 const SfxSimpleHint* pSimpleHint = dynamic_cast<const SfxSimpleHint*>(&rHint);
198 if ( pSimpleHint && pSimpleHint->GetId() == SFX_HINT_DEINITIALIZING )
200 // document must not be used anymore
201 aDocCache.Clear();
202 mbValid = false;
206 extern "C" SAL_DLLPUBLIC_EXPORT css::uno::XInterface* SAL_CALL
207 ScFunctionAcceess_get_implementation(css::uno::XComponentContext*, css::uno::Sequence<css::uno::Any> const &)
209 SolarMutexGuard aGuard;
210 ScDLL::Init();
211 return cppu::acquire(new ScFunctionAccess);
214 // XServiceInfo
215 OUString SAL_CALL ScFunctionAccess::getImplementationName() throw(uno::RuntimeException, std::exception)
217 return OUString("stardiv.StarCalc.ScFunctionAccess");
220 sal_Bool SAL_CALL ScFunctionAccess::supportsService( const OUString& rServiceName )
221 throw(uno::RuntimeException, std::exception)
223 return cppu::supportsService(this, rServiceName);
226 uno::Sequence<OUString> SAL_CALL ScFunctionAccess::getSupportedServiceNames()
227 throw(uno::RuntimeException, std::exception)
229 uno::Sequence<OUString> aRet(2);
230 OUString* pArray = aRet.getArray();
231 pArray[0] = SCFUNCTIONACCESS_SERVICE;
232 pArray[1] = SCDOCSETTINGS_SERVICE;
233 return aRet;
236 // XPropertySet (document settings)
238 uno::Reference<beans::XPropertySetInfo> SAL_CALL ScFunctionAccess::getPropertySetInfo()
239 throw(uno::RuntimeException, std::exception)
241 SolarMutexGuard aGuard;
242 static uno::Reference<beans::XPropertySetInfo> aRef(
243 new SfxItemPropertySetInfo( aPropertyMap ));
244 return aRef;
247 void SAL_CALL ScFunctionAccess::setPropertyValue(
248 const OUString& aPropertyName, const uno::Any& aValue )
249 throw(beans::UnknownPropertyException, beans::PropertyVetoException,
250 lang::IllegalArgumentException, lang::WrappedTargetException,
251 uno::RuntimeException, std::exception)
253 SolarMutexGuard aGuard;
255 if ( aPropertyName == "IsArrayFunction" )
257 if( !(aValue >>= mbArray) )
258 throw lang::IllegalArgumentException();
260 else
262 if ( !pOptions )
263 pOptions = new ScDocOptions();
265 // options aren't initialized from configuration - always get the same default behaviour
267 bool bDone = ScDocOptionsHelper::setPropertyValue( *pOptions, aPropertyMap, aPropertyName, aValue );
268 if (!bDone)
269 throw beans::UnknownPropertyException();
273 uno::Any SAL_CALL ScFunctionAccess::getPropertyValue( const OUString& aPropertyName )
274 throw(beans::UnknownPropertyException, lang::WrappedTargetException,
275 uno::RuntimeException, std::exception)
277 SolarMutexGuard aGuard;
279 if ( aPropertyName == "IsArrayFunction" )
280 return uno::Any( mbArray );
282 if ( !pOptions )
283 pOptions = new ScDocOptions();
285 // options aren't initialized from configuration - always get the same default behaviour
287 return ScDocOptionsHelper::getPropertyValue( *pOptions, aPropertyMap, aPropertyName );
290 SC_IMPL_DUMMY_PROPERTY_LISTENER( ScFunctionAccess )
292 // XFunctionAccess
294 static bool lcl_AddFunctionToken( ScTokenArray& rArray, const OUString& rName,const ScCompiler& rCompiler )
296 // function names are always case-insensitive
297 OUString aUpper = ScGlobal::pCharClass->uppercase(rName);
299 // same options as in ScCompiler::IsOpCode:
300 // 1. built-in function name
302 OpCode eOp = rCompiler.GetEnglishOpCode( aUpper );
303 if ( eOp != ocNone )
305 rArray.AddOpCode( eOp );
306 return true;
309 // 2. old add in functions
311 if (ScGlobal::GetFuncCollection()->findByName(aUpper))
313 rArray.AddExternal(aUpper.getStr());
314 return true;
317 // 3. new (uno) add in functions
319 OUString aIntName =
320 ScGlobal::GetAddInCollection()->FindFunction(aUpper, false);
321 if (!aIntName.isEmpty())
323 rArray.AddExternal(aIntName.getStr()); // international name
324 return true;
327 return false; // no valid function name
330 static void lcl_AddRef( ScTokenArray& rArray, long nStartRow, long nColCount, long nRowCount )
332 ScComplexRefData aRef;
333 aRef.InitRange(ScRange(0,nStartRow,0,nColCount-1,nStartRow+nRowCount-1,0));
334 rArray.AddDoubleReference(aRef);
337 class SimpleVisitor
339 protected:
340 bool mbArgError;
341 ScDocument* mpDoc;
342 public:
343 SimpleVisitor( ScDocument* pDoc ) : mbArgError( false ), mpDoc( pDoc ) {}
344 // could possibly just get away with JUST the following overload
345 // 1) virtual void visitElem( long& nCol, long& nRow, const double& elem )
346 // 2) virtual void visitElem( long& nCol, long& nRow, const OUString& elem )
347 // 3) virtual void visitElem( long& nCol, long& nRow, const uno::Any& elem )
348 // the other types methods are here just to reflect the orig code and for
349 // completeness.
351 void visitElem( long nCol, long nRow, const sal_Int16& elem )
353 mpDoc->SetValue( (SCCOL) nCol, (SCROW) nRow, 0, elem );
355 void visitElem( long nCol, long nRow, const sal_Int32& elem )
357 mpDoc->SetValue( (SCCOL) nCol, (SCROW) nRow, 0, elem );
359 void visitElem( long nCol, long nRow, const double& elem )
361 mpDoc->SetValue( (SCCOL) nCol, (SCROW) nRow, 0, elem );
363 void visitElem( long nCol, long nRow, const OUString& elem )
365 if (!elem.isEmpty())
367 ScSetStringParam aParam;
368 aParam.setTextInput();
369 mpDoc->SetString(ScAddress(nCol,nRow,0), elem, &aParam);
372 void visitElem( long nCol, long nRow, const uno::Any& rElement )
374 uno::TypeClass eElemClass = rElement.getValueTypeClass();
375 if ( eElemClass == uno::TypeClass_VOID )
377 // leave empty
379 else if ( eElemClass == uno::TypeClass_BYTE ||
380 eElemClass == uno::TypeClass_SHORT ||
381 eElemClass == uno::TypeClass_UNSIGNED_SHORT ||
382 eElemClass == uno::TypeClass_LONG ||
383 eElemClass == uno::TypeClass_UNSIGNED_LONG ||
384 eElemClass == uno::TypeClass_FLOAT ||
385 eElemClass == uno::TypeClass_DOUBLE )
387 // accept integer types because Basic passes a floating point
388 // variable as byte, short or long if it's an integer number.
389 double fVal(0.0);
390 rElement >>= fVal;
391 visitElem( nCol, nRow, fVal );
393 else if ( eElemClass == uno::TypeClass_STRING )
395 OUString aUStr;
396 rElement >>= aUStr;
397 visitElem( nCol, nRow, aUStr );
399 else
400 mbArgError = true;
402 bool hasArgError() const { return mbArgError; }
405 template< class seq >
406 class SequencesContainer
408 uno::Sequence< uno::Sequence< seq > > maSeq;
410 long& mrDocRow;
411 bool mbOverflow;
412 bool mbArgError;
413 ScDocument* mpDoc;
414 ScTokenArray& mrTokenArr;
416 public:
417 SequencesContainer( const uno::Any& rArg, ScTokenArray& rTokenArr, long& rDocRow, ScDocument* pDoc ) :
418 mrDocRow( rDocRow ), mbOverflow(false), mbArgError(false), mpDoc( pDoc ), mrTokenArr( rTokenArr )
420 rArg >>= maSeq;
423 void process()
425 SimpleVisitor aVisitor(mpDoc);
426 long nStartRow = mrDocRow;
427 long nRowCount = maSeq.getLength();
428 long nMaxColCount = 0;
429 const uno::Sequence< seq >* pRowArr = maSeq.getConstArray();
430 for ( long nRow=0; nRow<nRowCount; nRow++ )
432 long nColCount = pRowArr[nRow].getLength();
433 if ( nColCount > nMaxColCount )
434 nMaxColCount = nColCount;
435 const seq* pColArr = pRowArr[nRow].getConstArray();
436 for (long nCol=0; nCol<nColCount; nCol++)
437 if ( nCol <= MAXCOL && mrDocRow <= MAXROW )
438 aVisitor.visitElem( nCol, mrDocRow, pColArr[ nCol ] );
439 else
440 mbOverflow=true;
441 mrDocRow++;
443 mbArgError = aVisitor.hasArgError();
444 if ( nRowCount && nMaxColCount && !mbOverflow )
445 lcl_AddRef( mrTokenArr, nStartRow, nMaxColCount, nRowCount );
447 bool getOverflow() const { return mbOverflow; }
448 bool getArgError() const { return mbArgError; }
451 template <class T>
452 class ArrayOfArrayProc
454 public:
455 static void processSequences( ScDocument* pDoc, const uno::Any& rArg, ScTokenArray& rTokenArr,
456 long& rDocRow, bool& rArgErr, bool& rOverflow )
458 SequencesContainer< T > aContainer( rArg, rTokenArr, rDocRow, pDoc );
459 aContainer.process();
460 rArgErr = aContainer.getArgError();
461 rOverflow = aContainer.getOverflow();
465 uno::Any SAL_CALL ScFunctionAccess::callFunction( const OUString& aName,
466 const uno::Sequence<uno::Any>& aArguments )
467 throw (container::NoSuchElementException, lang::IllegalArgumentException,
468 uno::RuntimeException, std::exception)
470 SolarMutexGuard aGuard;
472 if (!mbValid)
473 throw uno::RuntimeException();
475 // use cached document if not in use, temporary document otherwise
476 // (deleted in ScTempDocSource dtor)
477 ScTempDocSource aSource( aDocCache );
478 ScDocument* pDoc = aSource.GetDocument();
479 const static SCTAB nTempSheet = 1;
480 // Create an extra tab to contain the Function Cell
481 // this will allow full rows to be used.
482 if ( !pDoc->HasTable( nTempSheet ) )
483 pDoc->MakeTable( nTempSheet );
485 /// TODO: check
486 ScAddress aAdr;
487 ScCompiler aCompiler(pDoc,aAdr);
488 aCompiler.SetGrammar(pDoc->GetGrammar());
490 // find function
492 ScTokenArray aTokenArr;
493 if ( !lcl_AddFunctionToken( aTokenArr, aName,aCompiler ) )
495 // function not found
496 throw container::NoSuchElementException();
499 // set options (null date, etc.)
501 if ( pOptions )
502 pDoc->SetDocOptions( *pOptions );
504 // add arguments to token array
506 bool bArgErr = false;
507 bool bOverflow = false;
508 long nDocRow = 0;
509 long nArgCount = aArguments.getLength();
510 const uno::Any* pArgArr = aArguments.getConstArray();
512 svl::SharedStringPool& rSPool = pDoc->GetSharedStringPool();
513 aTokenArr.AddOpCode(ocOpen);
514 for (long nPos=0; nPos<nArgCount; nPos++)
516 if ( nPos > 0 )
517 aTokenArr.AddOpCode(ocSep);
519 const uno::Any& rArg = pArgArr[nPos];
521 uno::TypeClass eClass = rArg.getValueTypeClass();
522 uno::Type aType = rArg.getValueType();
523 if ( eClass == uno::TypeClass_BYTE ||
524 eClass == uno::TypeClass_BOOLEAN ||
525 eClass == uno::TypeClass_SHORT ||
526 eClass == uno::TypeClass_UNSIGNED_SHORT ||
527 eClass == uno::TypeClass_LONG ||
528 eClass == uno::TypeClass_UNSIGNED_LONG ||
529 eClass == uno::TypeClass_FLOAT ||
530 eClass == uno::TypeClass_DOUBLE )
532 // accept integer types because Basic passes a floating point
533 // variable as byte, short or long if it's an integer number.
534 double fVal = 0;
535 rArg >>= fVal;
536 aTokenArr.AddDouble( fVal );
538 else if ( eClass == uno::TypeClass_STRING )
540 OUString aUStr;
541 rArg >>= aUStr;
542 aTokenArr.AddString(rSPool.intern(aUStr));
544 else if ( aType.equals( cppu::UnoType<uno::Sequence< uno::Sequence<sal_Int16> >>::get() ) )
546 ArrayOfArrayProc<sal_Int16>::processSequences( pDoc, rArg, aTokenArr, nDocRow, bArgErr, bOverflow );
548 else if ( aType.equals( cppu::UnoType<uno::Sequence< uno::Sequence<sal_Int32> >>::get() ) )
550 ArrayOfArrayProc<sal_Int32>::processSequences( pDoc, rArg, aTokenArr, nDocRow, bArgErr, bOverflow );
552 else if ( aType.equals( cppu::UnoType<uno::Sequence< uno::Sequence<double> >>::get() ) )
554 ArrayOfArrayProc<double>::processSequences( pDoc, rArg, aTokenArr, nDocRow, bArgErr, bOverflow );
556 else if ( aType.equals( cppu::UnoType<uno::Sequence< uno::Sequence<OUString> >>::get() ) )
558 ArrayOfArrayProc<OUString>::processSequences( pDoc, rArg, aTokenArr, nDocRow, bArgErr, bOverflow );
560 else if ( aType.equals( cppu::UnoType<uno::Sequence< uno::Sequence<uno::Any> >>::get() ) )
562 ArrayOfArrayProc<uno::Any>::processSequences( pDoc, rArg, aTokenArr, nDocRow, bArgErr, bOverflow );
564 else if ( aType.equals( cppu::UnoType<table::XCellRange>::get()) )
566 // currently, only our own cell ranges are supported
568 uno::Reference<table::XCellRange> xRange(rArg, uno::UNO_QUERY);
569 ScCellRangesBase* pImpl = ScCellRangesBase::getImplementation( xRange );
570 if ( pImpl )
572 ScDocument* pSrcDoc = pImpl->GetDocument();
573 const ScRangeList& rRanges = pImpl->GetRangeList();
574 if ( pSrcDoc && rRanges.size() == 1 )
576 ScRange aSrcRange = *rRanges[ 0 ];
578 long nStartRow = nDocRow;
579 long nColCount = aSrcRange.aEnd.Col() - aSrcRange.aStart.Col() + 1;
580 long nRowCount = aSrcRange.aEnd.Row() - aSrcRange.aStart.Row() + 1;
582 if ( nStartRow + nRowCount > MAXROWCOUNT )
583 bOverflow = true;
584 else
586 // copy data
587 if ( !lcl_CopyData( pSrcDoc, aSrcRange, pDoc, ScAddress( 0, (SCROW)nDocRow, 0 ) ) )
588 bOverflow = true;
591 nDocRow += nRowCount;
592 if ( !bOverflow )
593 lcl_AddRef( aTokenArr, nStartRow, nColCount, nRowCount );
595 else
596 bArgErr = true;
598 else
599 bArgErr = true;
601 else
602 bArgErr = true; // invalid type
604 aTokenArr.AddOpCode(ocClose);
605 aTokenArr.AddOpCode(ocStop);
607 // execute formula
609 uno::Any aRet;
610 if ( !bArgErr && !bOverflow && nDocRow <= MAXROWCOUNT )
612 ScAddress aFormulaPos( 0, 0, nTempSheet );
613 // GRAM_PODF_A1 doesn't really matter for the token array but fits with
614 // other API compatibility grammars.
615 ScFormulaCell* pFormula = new ScFormulaCell(
616 pDoc, aFormulaPos, aTokenArr, formula::FormulaGrammar::GRAM_PODF_A1,
617 (sal_uInt8)(mbArray ? MM_FORMULA : MM_NONE) );
618 pFormula = pDoc->SetFormulaCell(aFormulaPos, pFormula);
620 // call GetMatrix before GetErrCode because GetMatrix always recalculates
621 // if there is no matrix result
623 const ScMatrix* pMat = (mbArray && pFormula) ? pFormula->GetMatrix() : 0;
624 sal_uInt16 nErrCode = pFormula ? pFormula->GetErrCode() : errIllegalArgument;
625 if ( nErrCode == 0 )
627 if ( pMat )
629 // array result
630 ScRangeToSequence::FillMixedArray( aRet, pMat );
632 else if ( pFormula->IsValue() )
634 // numeric value
635 aRet <<= (double) pFormula->GetValue();
637 else
639 // string result
640 OUString aStrVal = pFormula->GetString().getString();
641 aRet <<= aStrVal;
644 else if ( nErrCode == NOTAVAILABLE )
646 // #N/A: leave result empty, no exception
648 else
650 // any other error: IllegalArgumentException
651 bArgErr = true;
654 pDoc->DeleteAreaTab( 0, 0, MAXCOL, MAXROW, 0, IDF_ALL );
655 pDoc->DeleteAreaTab( 0, 0, 0, 0, nTempSheet, IDF_ALL );
658 if (bOverflow)
659 throw uno::RuntimeException();
661 if (bArgErr)
662 throw lang::IllegalArgumentException();
664 return aRet;
667 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */