xref: /trunk/main/sc/source/core/tool/interpr2.cxx (revision 195598447694ec8542914a9b51ae9942e8ebacd9)
1 /**************************************************************
2  *
3  * Licensed to the Apache Software Foundation (ASF) under one
4  * or more contributor license agreements.  See the NOTICE file
5  * distributed with this work for additional information
6  * regarding copyright ownership.  The ASF licenses this file
7  * to you under the Apache License, Version 2.0 (the
8  * "License"); you may not use this file except in compliance
9  * with the License.  You may obtain a copy of the License at
10  *
11  *   http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing,
14  * software distributed under the License is distributed on an
15  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16  * KIND, either express or implied.  See the License for the
17  * specific language governing permissions and limitations
18  * under the License.
19  *
20  *************************************************************/
21 
22 // MARKER(update_precomp.py): autogen include statement, do not remove
23 #include "precompiled_sc.hxx"
24 
25 // INCLUDE ---------------------------------------------------------------
26 
27 #include <sfx2/linkmgr.hxx>
28 #include <sfx2/dispatch.hxx>
29 #include <sfx2/objsh.hxx>
30 #include <svl/stritem.hxx>
31 #include <svl/zforlist.hxx>
32 #include <rtl/logfile.hxx>
33 
34 #include "interpre.hxx"
35 #include "attrib.hxx"
36 #include "sc.hrc"
37 #include "ddelink.hxx"
38 #include "scmatrix.hxx"
39 #include "compiler.hxx"
40 #include "cell.hxx"
41 #include "document.hxx"
42 #include "dociter.hxx"
43 #include "docoptio.hxx"
44 #include "unitconv.hxx"
45 #include "globstr.hrc"
46 #include "hints.hxx"
47 #include "dpobject.hxx"
48 #include "postit.hxx"
49 
50 #include <string.h>
51 #include <math.h>
52 
53 #include <cmath>
54 
55 using namespace formula;
56 // STATIC DATA -----------------------------------------------------------
57 
58 #define D_TIMEFACTOR              86400.0
59 #define SCdEpsilon                1.0E-7
60 
61 //-----------------------------------------------------------------------------
62 // Date and Time
63 //-----------------------------------------------------------------------------
64 
GetDateSerial(sal_Int16 nYear,sal_Int16 nMonth,sal_Int16 nDay,bool bStrict)65 double ScInterpreter::GetDateSerial( sal_Int16 nYear, sal_Int16 nMonth, sal_Int16 nDay, bool bStrict )
66 {
67     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::GetDateSerial" );
68     if ( nYear < 100 && !bStrict )
69         nYear = pFormatter->ExpandTwoDigitYear( nYear );
70     // Do not use a default Date ctor here because it asks system time with a
71     // performance penalty.
72     sal_Int16 nY, nM, nD;
73     if (bStrict)
74         nY = nYear, nM = nMonth, nD = nDay;
75     else
76     {
77         if (nMonth > 0)
78         {
79             nY = nYear + (nMonth-1) / 12;
80             nM = ((nMonth-1) % 12) + 1;
81         }
82         else
83         {
84             nY = nYear + (nMonth-12) / 12;
85             nM = 12 - (-nMonth) % 12;
86         }
87         nD = 1;
88     }
89     Date aDate( nD, nM, nY);
90     if (!bStrict)
91         aDate += nDay - 1;
92     if (aDate.IsValid())
93         return (double) (aDate - *(pFormatter->GetNullDate()));
94     else
95     {
96         SetError(errNoValue);
97         return 0;
98     }
99 }
100 
101 //-----------------------------------------------------------------------------
102 // Functions
103 //-----------------------------------------------------------------------------
104 
ScGetActDate()105 void ScInterpreter::ScGetActDate()
106 {
107     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScGetActDate" );
108     nFuncFmtType = NUMBERFORMAT_DATE;
109     Date aActDate;
110     long nDiff = aActDate - *(pFormatter->GetNullDate());
111     PushDouble((double) nDiff);
112 }
113 
ScGetActTime()114 void ScInterpreter::ScGetActTime()
115 {
116     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScGetActTime" );
117     nFuncFmtType = NUMBERFORMAT_DATETIME;
118     Date aActDate;
119     long nDiff = aActDate - *(pFormatter->GetNullDate());
120     Time aActTime;
121     double nTime = ((double)aActTime.Get100Sec() / 100 +
122                     (double)(aActTime.GetSec()        +
123                             (aActTime.GetMin()  * 60) +
124                             (aActTime.GetHour() * 3600))) / D_TIMEFACTOR;
125     PushDouble( (double) nDiff + nTime );
126 }
127 
ScGetYear()128 void ScInterpreter::ScGetYear()
129 {
130     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScGetYear" );
131     Date aDate = *(pFormatter->GetNullDate());
132     aDate += (long) ::rtl::math::approxFloor(GetDouble());
133     PushDouble( (double) aDate.GetYear() );
134 }
135 
ScGetMonth()136 void ScInterpreter::ScGetMonth()
137 {
138     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScGetMonth" );
139     Date aDate = *(pFormatter->GetNullDate());
140     aDate += (long) ::rtl::math::approxFloor(GetDouble());
141     PushDouble( (double) aDate.GetMonth() );
142 }
143 
ScGetDay()144 void ScInterpreter::ScGetDay()
145 {
146     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScGetDay" );
147     Date aDate = *(pFormatter->GetNullDate());
148     aDate += (long)::rtl::math::approxFloor(GetDouble());
149     PushDouble((double) aDate.GetDay());
150 }
151 
ScGetMin()152 void ScInterpreter::ScGetMin()
153 {
154     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScGetMin" );
155     double fTime = GetDouble();
156     fTime -= ::rtl::math::approxFloor(fTime);       // Datumsanteil weg
157     long nVal = (long)::rtl::math::approxFloor(fTime*D_TIMEFACTOR+0.5) % 3600;
158     PushDouble( (double) (nVal/60) );
159 }
160 
ScGetSec()161 void ScInterpreter::ScGetSec()
162 {
163     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScGetSec" );
164     double fTime = GetDouble();
165     fTime -= ::rtl::math::approxFloor(fTime);       // Datumsanteil weg
166     long nVal = (long)::rtl::math::approxFloor(fTime*D_TIMEFACTOR+0.5) % 60;
167     PushDouble( (double) nVal );
168 }
169 
ScGetHour()170 void ScInterpreter::ScGetHour()
171 {
172     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScGetHour" );
173     double fTime = GetDouble();
174     fTime -= ::rtl::math::approxFloor(fTime);       // Datumsanteil weg
175     long nVal = (long)::rtl::math::approxFloor(fTime*D_TIMEFACTOR+0.5) / 3600;
176     PushDouble((double) nVal);
177 }
178 
ScGetDateValue()179 void ScInterpreter::ScGetDateValue()
180 {
181     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScGetDateValue" );
182     String aInputString = GetString();
183     sal_uInt32 nFIndex = 0;                 // damit default Land/Sprache
184     double fVal;
185     if (pFormatter->IsNumberFormat(aInputString, nFIndex, fVal))
186     {
187         short eType = pFormatter->GetType(nFIndex);
188         if (eType == NUMBERFORMAT_DATE || eType == NUMBERFORMAT_DATETIME)
189             PushDouble(::rtl::math::approxFloor(fVal));
190         else
191             PushIllegalArgument();
192     }
193     else
194         PushIllegalArgument();
195 }
196 
ScGetDayOfWeek()197 void ScInterpreter::ScGetDayOfWeek()
198 {
199     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScGetDayOfWeek" );
200     sal_uInt8 nParamCount = GetByte();
201     if ( MustHaveParamCount( nParamCount, 1, 2 ) )
202     {
203         short nFlag;
204         if (nParamCount == 2)
205             nFlag = (short) ::rtl::math::approxFloor(GetDouble());
206         else
207             nFlag = 1;
208 
209         Date aDate = *(pFormatter->GetNullDate());
210         aDate += (long)::rtl::math::approxFloor(GetDouble());
211         int nVal = (int) aDate.GetDayOfWeek();
212         if (nFlag == 1)
213         {
214             if (nVal == 6)
215                 nVal = 1;
216             else
217                 nVal += 2;
218         }
219         else if (nFlag == 2)
220             nVal += 1;
221         else if (nFlag >= 11 && nFlag <= 17)    // ODF 1.3: week starts on Monday (11) to Sunday (17), numbered 1-7
222             nVal = ((nVal + (18 - nFlag)) % 7) + 1;
223         PushInt( nVal );
224     }
225 }
226 
ScGetWeekOfYear()227 void ScInterpreter::ScGetWeekOfYear()
228 {
229     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScGetWeekOfYear" );
230     if ( MustHaveParamCount( GetByte(), 2 ) )
231     {
232         short nFlag = (short) ::rtl::math::approxFloor(GetDouble());
233 
234         Date aDate = *(pFormatter->GetNullDate());
235         aDate += (long)::rtl::math::approxFloor(GetDouble());
236         PushInt( (int) aDate.GetWeekOfYear( nFlag == 1 ? SUNDAY : MONDAY ));
237     }
238 }
239 
ScIsoWeekNum()240 void ScInterpreter::ScIsoWeekNum()
241 {
242     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScIsoWeekNum" );
243     if ( MustHaveParamCount( GetByte(), 1 ) )
244     {
245         Date aDate = *(pFormatter->GetNullDate());
246         aDate += (long)::rtl::math::approxFloor(GetDouble());
247         if ( !aDate.IsValid() )
248         {
249             PushIllegalArgument();
250             return;
251         }
252         // ISO 8601: Monday=1, week 1 = week containing Jan 4 (first Thursday)
253         // Use GetWeekOfYear with MONDAY start and 4 days minimum in first week
254         PushInt( (int) aDate.GetWeekOfYear( MONDAY, 4 ) );
255     }
256 }
257 
lcl_EasterSunday(sal_Int16 nYear,sal_Int16 & rDay,sal_Int16 & rMonth)258 static void lcl_EasterSunday( sal_Int16 nYear, sal_Int16& rDay, sal_Int16& rMonth )
259 {
260     // don't worry, be happy :)
261     int B,C,D,E,F,G,H,I,K,L,M,N,O;
262     N = nYear % 19;
263     B = int(nYear / 100);
264     C = nYear % 100;
265     D = int(B / 4);
266     E = B % 4;
267     F = int((B + 8) / 25);
268     G = int((B - F + 1) / 3);
269     H = (19 * N + B - D - G + 15) % 30;
270     I = int(C / 4);
271     K = C % 4;
272     L = (32 + 2 * E + 2 * I - H - K) % 7;
273     M = int((N + 11 * H + 22 * L) / 451);
274     O = H + L - 7 * M + 114;
275     rDay = sal::static_int_cast<sal_Int16>( O % 31 + 1 );
276     rMonth = sal::static_int_cast<sal_Int16>( int(O / 31) );
277 }
278 
ScEasterSunday()279 void ScInterpreter::ScEasterSunday()
280 {
281     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScEasterSunday" );
282     nFuncFmtType = NUMBERFORMAT_DATE;
283     sal_uInt8 nParamCount = GetByte();
284     if ( MustHaveParamCount( nParamCount, 0, 1 ) )
285     {
286         sal_Int16 nDay, nMonth, nYear;
287         if ( nParamCount == 1 )
288         {
289             double fYear = ::rtl::math::approxFloor( GetDouble() );
290             // ODF 1.4 Part 4 6.10.8: 1583 <= Year <= 9956; checked before the cast to sal_Int16, which would wrap
291             if ( fYear < 0.0 || fYear > 9956.0 )
292             {
293                 PushIllegalArgument();
294                 return;
295             }
296             nYear = (sal_Int16) fYear;
297             if ( nYear < 100 )
298                 nYear = pFormatter->ExpandTwoDigitYear( nYear );
299             lcl_EasterSunday( nYear, nDay, nMonth );
300             PushDouble( GetDateSerial( nYear, nMonth, nDay, true ) );
301         }
302         else
303         {
304             // no Year: the next Easter Sunday on or after today
305             Date aActDate;
306             double fToday = (double) ( aActDate - *(pFormatter->GetNullDate()) );
307             nYear = aActDate.GetYear();
308             lcl_EasterSunday( nYear, nDay, nMonth );
309             double fEaster = GetDateSerial( nYear, nMonth, nDay, true );
310             if ( fEaster < fToday )
311             {
312                 lcl_EasterSunday( ++nYear, nDay, nMonth );
313                 fEaster = GetDateSerial( nYear, nMonth, nDay, true );
314             }
315             PushDouble( fEaster );
316         }
317     }
318 }
319 
ScGetDate()320 void ScInterpreter::ScGetDate()
321 {
322     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScGetDate" );
323     nFuncFmtType = NUMBERFORMAT_DATE;
324     if ( MustHaveParamCount( GetByte(), 3 ) )
325     {
326         sal_Int16 nDay   = (sal_Int16) ::rtl::math::approxFloor(GetDouble());
327         sal_Int16 nMonth = (sal_Int16) ::rtl::math::approxFloor(GetDouble());
328         sal_Int16 nYear  = (sal_Int16) ::rtl::math::approxFloor(GetDouble());
329         if (nYear < 0)
330             PushIllegalArgument();
331         else
332         {
333             PushDouble(GetDateSerial(nYear, nMonth, nDay, false));
334         }
335     }
336 }
337 
ScGetTime()338 void ScInterpreter::ScGetTime()
339 {
340     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScGetTime" );
341     nFuncFmtType = NUMBERFORMAT_TIME;
342     if ( MustHaveParamCount( GetByte(), 3 ) )
343     {
344         double nSec = GetDouble();
345         double nMin = GetDouble();
346         double nHour = GetDouble();
347         double fTime = fmod( (nHour * 3600) + (nMin * 60) + nSec, D_TIMEFACTOR) / D_TIMEFACTOR;
348         if (fTime < 0)
349             PushIllegalArgument();
350         else
351             PushDouble( fTime);
352     }
353 }
354 
ScGetDiffDate()355 void ScInterpreter::ScGetDiffDate()
356 {
357     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScGetDiffDate" );
358     if ( MustHaveParamCount( GetByte(), 2 ) )
359     {
360         double nDate2 = GetDouble();
361         double nDate1 = GetDouble();
362         PushDouble(nDate1 - nDate2);
363     }
364 }
365 
ScGetDiffDate360()366 void ScInterpreter::ScGetDiffDate360()
367 {
368     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScGetDiffDate360" );
369     /* Implementation follows
370      * http://www.bondmarkets.com/eCommerce/SMD_Fields_030802.pdf
371      * Appendix B: Day-Count Bases, there are 7 different ways to calculate the
372      * 30-days count. That document also claims that Excel implements the "PSA
373      * 30" or "NASD 30" method (funny enough they also state that Excel is the
374      * only tool that does so).
375      *
376      * Note that the definition given in
377      * http://msdn.microsoft.com/library/en-us/office97/html/SEB7C.asp
378      * is _not_ the way how it is actually calculated by Excel (that would not
379      * even match any of the 7 methods mentioned above) and would result in the
380      * following test cases producing wrong results according to that appendix B:
381      *
382      * 28-Feb-95  31-Aug-95  181 instead of 180
383      * 29-Feb-96  31-Aug-96  181 instead of 180
384      * 30-Jan-96  31-Mar-96   61 instead of  60
385      * 31-Jan-96  31-Mar-96   61 instead of  60
386      *
387      * Still, there is a difference between Calc and Excel:
388      * In Excel:
389      * 02-Feb-99 31-Mar-00 results in  419
390      * 31-Mar-00 02-Feb-99 results in -418
391      * In Calc the result is 419 respectively -419. I consider the -418 a bug in Excel.
392      */
393 
394     sal_uInt8 nParamCount = GetByte();
395     if ( MustHaveParamCount( nParamCount, 2, 3 ) )
396     {
397         sal_Bool bFlag;
398         if (nParamCount == 3)
399             bFlag = GetBool();
400         else
401             bFlag = sal_False;
402         double nDate2 = GetDouble();
403         double nDate1 = GetDouble();
404         double fSign;
405         if (nGlobalError)
406             PushError( nGlobalError);
407         else
408         {
409             // #i84934# only for non-US European algorithm swap dates. Else
410             // follow Excel's meaningless extrapolation for "interoperability".
411             if (bFlag && (nDate2 < nDate1))
412             {
413                 fSign = nDate1;
414                 nDate1 = nDate2;
415                 nDate2 = fSign;
416                 fSign = -1.0;
417             }
418             else
419                 fSign = 1.0;
420             Date aDate1 = *(pFormatter->GetNullDate());
421             aDate1 += (long) ::rtl::math::approxFloor(nDate1);
422             Date aDate2 = *(pFormatter->GetNullDate());
423             aDate2 += (long) ::rtl::math::approxFloor(nDate2);
424             if (aDate1.GetDay() == 31)
425                 aDate1 -= (sal_uLong) 1;
426             else if (!bFlag)
427             {
428                 if (aDate1.GetMonth() == 2)
429                 {
430                     switch ( aDate1.GetDay() )
431                     {
432                         case 28 :
433                             if ( !aDate1.IsLeapYear() )
434                                 aDate1.SetDay(30);
435                         break;
436                         case 29 :
437                             aDate1.SetDay(30);
438                         break;
439                     }
440                 }
441             }
442             if (aDate2.GetDay() == 31)
443             {
444                 if (!bFlag )
445                 {
446                     if (aDate1.GetDay() == 30)
447                         aDate2 -= (sal_uLong) 1;
448                 }
449                 else
450                     aDate2.SetDay(30);
451             }
452             PushDouble( fSign * (double)
453                 (  (double) aDate2.GetDay() + (double) aDate2.GetMonth() * 30.0 +
454                    (double) aDate2.GetYear() * 360.0
455                  - (double) aDate1.GetDay() - (double) aDate1.GetMonth() * 30.0
456                  - (double)aDate1.GetYear() * 360.0) );
457         }
458     }
459 }
460 
ScDateDif()461 void ScInterpreter::ScDateDif()
462 {
463     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScDateDif" );
464     if ( MustHaveParamCount( GetByte(), 3 ) )
465     {
466         String aFormat( GetString() );
467         double fEnd   = ::rtl::math::approxFloor( GetDouble() );
468         double fStart = ::rtl::math::approxFloor( GetDouble() );
469         if ( nGlobalError )
470         {
471             PushError( nGlobalError );
472             return;
473         }
474         if ( fStart > fEnd )
475         {
476             PushIllegalArgument();
477             return;
478         }
479 
480         Date aFrom = *(pFormatter->GetNullDate());
481         aFrom += (long) fStart;
482         Date aTo = *(pFormatter->GetNullDate());
483         aTo += (long) fEnd;
484         if ( !aFrom.IsValid() || !aTo.IsValid() )
485         {
486             PushIllegalArgument();
487             return;
488         }
489 
490         // Complete months: the end day must reach the start day.
491         long nMonths = ((long)aTo.GetYear() - (long)aFrom.GetYear()) * 12
492                      + ((long)aTo.GetMonth() - (long)aFrom.GetMonth());
493         if ( aTo.GetDay() < aFrom.GetDay() )
494             --nMonths;
495 
496         aFormat.ToLowerAscii();
497         double fResult;
498         if ( aFormat.EqualsAscii( "d" ) )
499             fResult = (double)(aTo - aFrom);
500         else if ( aFormat.EqualsAscii( "m" ) )
501             fResult = (double)nMonths;
502         else if ( aFormat.EqualsAscii( "y" ) )
503             fResult = (double)(nMonths / 12);
504         else if ( aFormat.EqualsAscii( "ym" ) )
505             fResult = (double)(nMonths % 12);
506         else if ( aFormat.EqualsAscii( "md" ) )
507         {
508             // As Excel: borrow the length of the month before the end month,
509             // which gives a negative result for some month ends.
510             long nDays = (long)aTo.GetDay() - (long)aFrom.GetDay();
511             if ( nDays < 0 )
512             {
513                 Date aPrev( 1, aTo.GetMonth(), aTo.GetYear() );
514                 aPrev -= 1;
515                 nDays += aPrev.GetDaysInMonth();
516             }
517             fResult = (double)nDays;
518         }
519         else if ( aFormat.EqualsAscii( "yd" ) )
520         {
521             // As Excel: move the end date into the first year that does not put it
522             // before the start date; February 29 becomes March 1 in other years.
523             sal_uInt16 nYear = aFrom.GetYear();
524             if ( aTo.GetMonth() < aFrom.GetMonth() ||
525                     (aTo.GetMonth() == aFrom.GetMonth() && aTo.GetDay() < aFrom.GetDay()) )
526                 ++nYear;
527             Date aEnd( 1, aTo.GetMonth(), nYear );
528             aEnd += (long)aTo.GetDay() - 1;
529             fResult = (double)(aEnd - aFrom);
530         }
531         else
532         {
533             PushIllegalArgument();
534             return;
535         }
536         PushDouble( fResult );
537     }
538 }
539 
ScGetTimeValue()540 void ScInterpreter::ScGetTimeValue()
541 {
542     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScGetTimeValue" );
543     String aInputString = GetString();
544     sal_uInt32 nFIndex = 0;                 // damit default Land/Sprache
545     double fVal;
546     if (pFormatter->IsNumberFormat(aInputString, nFIndex, fVal))
547     {
548         short eType = pFormatter->GetType(nFIndex);
549         if (eType == NUMBERFORMAT_TIME || eType == NUMBERFORMAT_DATETIME)
550         {
551             double fDateVal = rtl::math::approxFloor(fVal);
552             double fTimeVal = fVal - fDateVal;
553             PushDouble(fTimeVal);
554         }
555         else
556             PushIllegalArgument();
557     }
558     else
559         PushIllegalArgument();
560 }
561 
ScPlusMinus()562 void ScInterpreter::ScPlusMinus()
563 {
564     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScPlusMinus" );
565     double nVal = GetDouble();
566     short n = 0;
567     if (nVal < 0.0)
568         n = -1;
569     else if (nVal > 0.0)
570         n = 1;
571     PushInt( n );
572 }
573 
ScAbs()574 void ScInterpreter::ScAbs()
575 {
576     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScAbs" );
577     PushDouble(fabs(GetDouble()));
578 }
579 
ScInt()580 void ScInterpreter::ScInt()
581 {
582     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScInt" );
583     PushDouble(::rtl::math::approxFloor(GetDouble()));
584 }
585 
586 
RoundNumber(rtl_math_RoundingMode eMode)587 void ScInterpreter::RoundNumber( rtl_math_RoundingMode eMode )
588 {
589     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::RoundNumber" );
590     sal_uInt8 nParamCount = GetByte();
591     if ( MustHaveParamCount( nParamCount, 1, 2 ) )
592     {
593         double fVal = 0.0;
594         if (nParamCount == 1)
595             fVal = ::rtl::math::round( GetDouble(), 0, eMode );
596         else
597         {
598             sal_Int32 nDec = (sal_Int32) ::rtl::math::approxFloor(GetDouble());
599             if( nDec < -20 || nDec > 20 )
600                 PushIllegalArgument();
601             else
602                 fVal = ::rtl::math::round( GetDouble(), (short)nDec, eMode );
603         }
604         PushDouble(fVal);
605     }
606 }
607 
ScRound()608 void ScInterpreter::ScRound()
609 {
610     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScRound" );
611     RoundNumber( rtl_math_RoundingMode_Corrected );
612 }
613 
ScRoundDown()614 void ScInterpreter::ScRoundDown()
615 {
616     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScRoundDown" );
617     RoundNumber( rtl_math_RoundingMode_Down );
618 }
619 
ScRoundUp()620 void ScInterpreter::ScRoundUp()
621 {
622     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScRoundUp" );
623     RoundNumber( rtl_math_RoundingMode_Up );
624 }
625 
ScCeil()626 void ScInterpreter::ScCeil()
627 {
628     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScCeil" );
629     sal_uInt8 nParamCount = GetByte();
630     if ( MustHaveParamCount( nParamCount, 2, 3 ) )
631     {
632         sal_Bool bAbs = ( nParamCount == 3 ? GetBool() : sal_False );
633         double fDec = GetDouble();
634         double fVal = GetDouble();
635         if ( fDec == 0.0 )
636             PushInt(0);
637         else if (fVal*fDec < 0.0)
638             PushIllegalArgument();
639         else
640         {
641             if ( !bAbs && fVal < 0.0 )
642                 PushDouble(::rtl::math::approxFloor(fVal/fDec) * fDec);
643             else
644                 PushDouble(::rtl::math::approxCeil(fVal/fDec) * fDec);
645         }
646     }
647 }
648 
ScFloor()649 void ScInterpreter::ScFloor()
650 {
651     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScFloor" );
652     sal_uInt8 nParamCount = GetByte();
653     if ( MustHaveParamCount( nParamCount, 2, 3 ) )
654     {
655         sal_Bool bAbs = ( nParamCount == 3 ? GetBool() : sal_False );
656         double fDec = GetDouble();
657         double fVal = GetDouble();
658         if ( fDec == 0.0 )
659             PushInt(0);
660         else if (fVal*fDec < 0.0)
661             PushIllegalArgument();
662         else
663         {
664             if ( !bAbs && fVal < 0.0 )
665                 PushDouble(::rtl::math::approxCeil(fVal/fDec) * fDec);
666             else
667                 PushDouble(::rtl::math::approxFloor(fVal/fDec) * fDec);
668         }
669     }
670 }
671 
ScEven()672 void ScInterpreter::ScEven()
673 {
674     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScEven" );
675     double fVal = GetDouble();
676     if (fVal < 0.0)
677         PushDouble(::rtl::math::approxFloor(fVal/2.0) * 2.0);
678     else
679         PushDouble(::rtl::math::approxCeil(fVal/2.0) * 2.0);
680 }
681 
ScOdd()682 void ScInterpreter::ScOdd()
683 {
684     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScOdd" );
685     double fVal = GetDouble();
686     if (fVal >= 0.0)
687     {
688         fVal = ::rtl::math::approxCeil(fVal);
689         if (fmod(fVal, 2.0) == 0.0)
690             fVal += 1.0;
691     }
692     else
693     {
694         fVal = ::rtl::math::approxFloor(fVal);
695         if (fmod(fVal, 2.0) == 0.0)
696             fVal -= 1.0;
697     }
698     PushDouble(fVal);
699 }
700 
ScArcTan2()701 void ScInterpreter::ScArcTan2()
702 {
703     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScArcTan2" );
704     if ( MustHaveParamCount( GetByte(), 2 ) )
705     {
706         double nVal2 = GetDouble();
707         double nVal1 = GetDouble();
708         PushDouble(atan2(nVal2, nVal1));
709     }
710 }
711 
ScLog()712 void ScInterpreter::ScLog()
713 {
714     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScLog" );
715     sal_uInt8 nParamCount = GetByte();
716     if ( MustHaveParamCount( nParamCount, 1, 2 ) )
717     {
718         double nBase;
719         if (nParamCount == 2)
720             nBase = GetDouble();
721         else
722             nBase = 10.0;
723         double nVal = GetDouble();
724         if (nVal > 0.0 && nBase > 0.0 && nBase != 1.0)
725             PushDouble(log(nVal) / log(nBase));
726         else
727             PushIllegalArgument();
728     }
729 }
730 
ScLn()731 void ScInterpreter::ScLn()
732 {
733     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScLn" );
734     double fVal = GetDouble();
735     if (fVal > 0.0)
736         PushDouble(log(fVal));
737     else
738         PushIllegalArgument();
739 }
740 
ScLog10()741 void ScInterpreter::ScLog10()
742 {
743     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScLog10" );
744     double fVal = GetDouble();
745     if (fVal > 0.0)
746         PushDouble(log10(fVal));
747     else
748         PushIllegalArgument();
749 }
750 
ScNPV()751 void ScInterpreter::ScNPV()
752 {
753     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScNPV" );
754     nFuncFmtType = NUMBERFORMAT_CURRENCY;
755     short nParamCount = GetByte();
756     if ( MustHaveParamCount( nParamCount, 2, 31 ) )
757     {
758         double nVal = 0.0;
759         // Wir drehen den Stack um!!
760         FormulaToken* pTemp[ 31 ];
761         for( short i = 0; i < nParamCount; i++ )
762             pTemp[ i ] = pStack[ sp - i - 1 ];
763         memcpy( &pStack[ sp - nParamCount ], pTemp, nParamCount * sizeof( FormulaToken* ) );
764         if (nGlobalError == 0)
765         {
766             double  nCount = 1.0;
767             double  nZins = GetDouble();
768             --nParamCount;
769             size_t nRefInList = 0;
770             ScRange aRange;
771             while (nParamCount-- > 0)
772             {
773                 switch (GetStackType())
774                 {
775                     case svDouble :
776                     {
777                         nVal += (GetDouble() / pow(1.0 + nZins, (double)nCount));
778                         nCount++;
779                     }
780                     break;
781                     case svSingleRef :
782                     {
783                         ScAddress aAdr;
784                         PopSingleRef( aAdr );
785                         ScBaseCell* pCell = GetCell( aAdr );
786                         if (!HasCellEmptyData(pCell) && HasCellValueData(pCell))
787                         {
788                             double nCellVal = GetCellValue( aAdr, pCell );
789                             nVal += (nCellVal / pow(1.0 + nZins, (double)nCount));
790                             nCount++;
791                         }
792                     }
793                     break;
794                     case svDoubleRef :
795                     case svRefList :
796                     {
797                         sal_uInt16 nErr = 0;
798                         double nCellVal;
799                         PopDoubleRef( aRange, nParamCount, nRefInList);
800                         ScHorizontalValueIterator aValIter( pDok, aRange, glSubTotal);
801                         while ((nErr == 0) && aValIter.GetNext(nCellVal, nErr))
802                         {
803                             nVal += (nCellVal / pow(1.0 + nZins, (double)nCount));
804                             nCount++;
805                         }
806                         if ( nErr != 0 )
807                             SetError(nErr);
808                     }
809                     break;
810                     default : SetError(errIllegalParameter); break;
811                 }
812             }
813         }
814         PushDouble(nVal);
815     }
816 }
817 
ScIRR()818 void ScInterpreter::ScIRR()
819 {
820     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScIRR" );
821     double fSchaetzwert;
822     nFuncFmtType = NUMBERFORMAT_PERCENT;
823     sal_uInt8 nParamCount = GetByte();
824     if ( !MustHaveParamCount( nParamCount, 1, 2 ) )
825         return;
826     if (nParamCount == 2)
827         fSchaetzwert = GetDouble();
828     else
829         fSchaetzwert = 0.1;
830     sal_uInt16 sPos = sp;                       // Stack-Position merken
831     double fEps = 1.0;
832     double x, xNeu, fWert, fZaehler, fNenner, nCount;
833     if (fSchaetzwert == -1.0)
834         x = 0.1;                            // default gegen Nulldivisionen
835     else
836         x = fSchaetzwert;                   // Startwert
837     switch (GetStackType())
838     {
839         case svDoubleRef :
840         break;
841         default:
842         {
843             PushIllegalParameter();
844             return;
845         }
846     }
847     const sal_uInt16 nIterationsMax = 20;
848     sal_uInt16 nItCount = 0;
849     ScRange aRange;
850     while (fEps > SCdEpsilon && nItCount < nIterationsMax)
851     {                                       // Newton-Verfahren:
852         sp = sPos;                          // Stack zurücksetzen
853         nCount = 0.0;
854         fZaehler = 0.0;
855         fNenner = 0.0;
856         sal_uInt16 nErr = 0;
857         PopDoubleRef( aRange );
858         ScValueIterator aValIter(pDok, aRange, glSubTotal);
859         if (aValIter.GetFirst(fWert, nErr))
860         {
861             fZaehler +=           fWert / pow(1.0+x,(double)nCount);
862             fNenner  += -nCount * fWert / pow(1.0+x,nCount+1.0);
863             nCount++;
864             while ((nErr == 0) && aValIter.GetNext(fWert, nErr))
865             {
866                 fZaehler +=           fWert / pow(1.0+x,(double)nCount);
867                 fNenner  += -nCount * fWert / pow(1.0+x,nCount+1.0);
868                 nCount++;
869             }
870             SetError(nErr);
871         }
872         xNeu = x - fZaehler / fNenner;  // x(i+1) = x(i)-f(x(i))/f'(x(i))
873         nItCount++;
874         fEps = fabs(xNeu - x);
875         x = xNeu;
876     }
877     if (fSchaetzwert == 0.0 && fabs(x) < SCdEpsilon)
878         x = 0.0;                        // auf Null normieren
879     if (fEps < SCdEpsilon)
880         PushDouble(x);
881     else
882         PushError( errNoConvergence);
883 }
884 
ScMIRR()885 void ScInterpreter::ScMIRR()
886 {   // range_of_values ; rate_invest ; rate_reinvest
887     nFuncFmtType = NUMBERFORMAT_PERCENT;
888     if( MustHaveParamCount( GetByte(), 3 ) )
889     {
890         double fRate1_reinvest = GetDouble() + 1;
891         double fNPV_reinvest = 0.0;
892         double fPow_reinvest = 1.0;
893 
894         double fRate1_invest = GetDouble() + 1;
895         double fNPV_invest = 0.0;
896         double fPow_invest = 1.0;
897 
898         ScRange aRange;
899         PopDoubleRef( aRange );
900 
901         if( nGlobalError )
902             PushError( nGlobalError);
903         else
904         {
905             ScValueIterator aValIter( pDok, aRange, glSubTotal );
906             double fCellValue;
907             sal_uLong nCount = 0;
908             sal_uInt16 nIterError = 0;
909 
910             sal_Bool bLoop = aValIter.GetFirst( fCellValue, nIterError );
911             while( bLoop )
912             {
913                 if( fCellValue > 0.0 )          // reinvestments
914                     fNPV_reinvest += fCellValue * fPow_reinvest;
915                 else if( fCellValue < 0.0 )     // investments
916                     fNPV_invest += fCellValue * fPow_invest;
917                 fPow_reinvest /= fRate1_reinvest;
918                 fPow_invest /= fRate1_invest;
919                 nCount++;
920 
921                 bLoop = aValIter.GetNext( fCellValue, nIterError );
922             }
923             if( nIterError )
924                 PushError( nIterError );
925             else
926             {
927                 double fResult = -fNPV_reinvest / fNPV_invest;
928                 fResult *= pow( fRate1_reinvest, (double) nCount - 1 );
929                 fResult = pow( fResult, 1.0 / (nCount - 1) );
930                 PushDouble( fResult - 1.0 );
931             }
932         }
933     }
934 }
935 
936 
ScISPMT()937 void ScInterpreter::ScISPMT()
938 {   // rate ; period ; total_periods ; invest
939     if( MustHaveParamCount( GetByte(), 4 ) )
940     {
941         double fInvest = GetDouble();
942         double fTotal = GetDouble();
943         double fPeriod = GetDouble();
944         double fRate = GetDouble();
945 
946         if( nGlobalError )
947             PushError( nGlobalError);
948         else
949             PushDouble( fInvest * fRate * (fPeriod / fTotal - 1.0) );
950     }
951 }
952 
953 
954 //----------------------- Finanzfunktionen ------------------------------------
955 
ScGetBw(double fZins,double fZzr,double fRmz,double fZw,double fF)956 double ScInterpreter::ScGetBw(double fZins, double fZzr, double fRmz,
957                               double fZw, double fF)
958 {
959     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScMIRR" );
960     double fBw;
961     if (fZins == 0.0)
962         fBw = fZw + fRmz * fZzr;
963     else if (fF > 0.0)
964         fBw = (fZw * pow(1.0 + fZins, -fZzr))
965                 + (fRmz * (1.0 - pow(1.0 + fZins, -fZzr + 1.0)) / fZins)
966                 + fRmz;
967     else
968         fBw = (fZw * pow(1.0 + fZins, -fZzr))
969                 + (fRmz * (1.0 - pow(1.0 + fZins, -fZzr)) / fZins);
970     return -fBw;
971 }
972 
ScBW()973 void ScInterpreter::ScBW()
974 {
975     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScBW" );
976     nFuncFmtType = NUMBERFORMAT_CURRENCY;
977     double nRmz, nZzr, nZins, nZw = 0, nFlag = 0;
978     sal_uInt8 nParamCount = GetByte();
979     if ( !MustHaveParamCount( nParamCount, 3, 5 ) )
980         return;
981     if (nParamCount == 5)
982         nFlag = GetDouble();
983     if (nParamCount >= 4)
984         nZw   = GetDouble();
985     nRmz  = GetDouble();
986     nZzr  = GetDouble();
987     nZins = GetDouble();
988     PushDouble(ScGetBw(nZins, nZzr, nRmz, nZw, nFlag));
989 }
990 
ScDIA()991 void ScInterpreter::ScDIA()
992 {
993     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScDIA" );
994     nFuncFmtType = NUMBERFORMAT_CURRENCY;
995     if ( MustHaveParamCount( GetByte(), 4 ) )
996     {
997         double nZr = GetDouble();
998         double nDauer = GetDouble();
999         double nRest = GetDouble();
1000         double nWert = GetDouble();
1001         double nDia = ((nWert - nRest) * (nDauer - nZr + 1.0)) /
1002                       ((nDauer * (nDauer + 1.0)) / 2.0);
1003         PushDouble(nDia);
1004     }
1005 }
1006 
ScGetGDA(double fWert,double fRest,double fDauer,double fPeriode,double fFaktor)1007 double ScInterpreter::ScGetGDA(double fWert, double fRest, double fDauer,
1008                 double fPeriode, double fFaktor)
1009 {
1010     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScGetGDA" );
1011     double fGda, fZins, fAlterWert, fNeuerWert;
1012     fZins = fFaktor / fDauer;
1013     if (fZins >= 1.0)
1014     {
1015         fZins = 1.0;
1016         if (fPeriode == 1.0)
1017             fAlterWert = fWert;
1018         else
1019             fAlterWert = 0.0;
1020     }
1021     else
1022         fAlterWert = fWert * pow(1.0 - fZins, fPeriode - 1.0);
1023     fNeuerWert = fWert * pow(1.0 - fZins, fPeriode);
1024 
1025     if (fNeuerWert < fRest)
1026         fGda = fAlterWert - fRest;
1027     else
1028         fGda = fAlterWert - fNeuerWert;
1029     if (fGda < 0.0)
1030         fGda = 0.0;
1031     return fGda;
1032 }
1033 
ScGDA()1034 void ScInterpreter::ScGDA()
1035 {
1036     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScGDA" );
1037     nFuncFmtType = NUMBERFORMAT_CURRENCY;
1038     sal_uInt8 nParamCount = GetByte();
1039     if ( MustHaveParamCount( nParamCount, 4, 5 ) )
1040     {
1041         double nFaktor;
1042         if (nParamCount == 5)
1043             nFaktor = GetDouble();
1044         else
1045             nFaktor = 2.0;
1046         double nPeriode = GetDouble();
1047         double nDauer   = GetDouble();
1048         double nRest    = GetDouble();
1049         double nWert    = GetDouble();
1050         if (nWert < 0.0 || nRest < 0.0 || nFaktor <= 0.0 || nRest > nWert
1051                         || nPeriode < 1.0 || nPeriode > nDauer)
1052             PushIllegalArgument();
1053         else
1054             PushDouble(ScGetGDA(nWert, nRest, nDauer, nPeriode, nFaktor));
1055     }
1056 }
1057 
ScGDA2()1058 void ScInterpreter::ScGDA2()
1059 {
1060     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScGDA2" );
1061     nFuncFmtType = NUMBERFORMAT_CURRENCY;
1062     sal_uInt8 nParamCount = GetByte();
1063     if ( !MustHaveParamCount( nParamCount, 4, 5 ) )
1064         return ;
1065     double nMonate;
1066     if (nParamCount == 4)
1067         nMonate = 12.0;
1068     else
1069         nMonate = ::rtl::math::approxFloor(GetDouble());
1070     double nPeriode = GetDouble();
1071     double nDauer = GetDouble();
1072     double nRest = GetDouble();
1073     double nWert = GetDouble();
1074     if (nMonate < 1.0 || nMonate > 12.0 || nDauer > 1200.0 || nRest < 0.0 ||
1075         nPeriode > (nDauer + 1.0) || nRest > nWert || nWert < 0.0)
1076     {
1077         PushIllegalArgument();
1078         return;
1079     }
1080     double nAbRate = 1.0 - pow(nRest / nWert, 1.0 / nDauer);
1081     nAbRate = ::rtl::math::approxFloor((nAbRate * 1000.0) + 0.5) / 1000.0;
1082     double nErsteAbRate = nWert * nAbRate * nMonate / 12.0;
1083     double nGda2 = 0.0;
1084     if (::rtl::math::approxFloor(nPeriode) == 1)
1085         nGda2 = nErsteAbRate;
1086     else
1087     {
1088         double nSummAbRate = nErsteAbRate;
1089         double nMin = nDauer;
1090         if (nMin > nPeriode) nMin = nPeriode;
1091         sal_uInt16 iMax = (sal_uInt16)::rtl::math::approxFloor(nMin);
1092         for (sal_uInt16 i = 2; i <= iMax; i++)
1093         {
1094             nGda2 = (nWert - nSummAbRate) * nAbRate;
1095             nSummAbRate += nGda2;
1096         }
1097         if (nPeriode > nDauer)
1098             nGda2 = ((nWert - nSummAbRate) * nAbRate * (12.0 - nMonate)) / 12.0;
1099     }
1100     PushDouble(nGda2);
1101 }
1102 
1103 
ScInterVDB(double fWert,double fRest,double fDauer,double fDauer1,double fPeriode,double fFaktor)1104 double ScInterpreter::ScInterVDB(double fWert,double fRest,double fDauer,
1105                              double fDauer1,double fPeriode,double fFaktor)
1106 {
1107     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScInterVDB" );
1108     double fVdb=0;
1109     double fIntEnd   = ::rtl::math::approxCeil(fPeriode);
1110     sal_uLong nLoopEnd   = (sal_uLong) fIntEnd;
1111 
1112     double fTerm, fLia;
1113     double fRestwert = fWert - fRest;
1114     sal_Bool bNowLia = sal_False;
1115 
1116     double fGda;
1117     sal_uLong i;
1118     fLia=0;
1119     for ( i = 1; i <= nLoopEnd; i++)
1120     {
1121         if(!bNowLia)
1122         {
1123             fGda = ScGetGDA(fWert, fRest, fDauer, (double) i, fFaktor);
1124             fLia = fRestwert/ (fDauer1 - (double) (i-1));
1125 
1126             if (fLia > fGda)
1127             {
1128                 fTerm = fLia;
1129                 bNowLia = sal_True;
1130             }
1131             else
1132             {
1133                 fTerm = fGda;
1134                 fRestwert -= fGda;
1135             }
1136         }
1137         else
1138         {
1139             fTerm = fLia;
1140         }
1141 
1142         if ( i == nLoopEnd)
1143             fTerm *= ( fPeriode + 1.0 - fIntEnd );
1144 
1145         fVdb += fTerm;
1146     }
1147     return fVdb;
1148 }
1149 
1150 
DblMin(double a,double b)1151 inline double DblMin( double a, double b )
1152 {
1153     return (a < b) ? a : b;
1154 }
1155 
ScVDB()1156 void ScInterpreter::ScVDB()
1157 {
1158     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScVDB" );
1159     nFuncFmtType = NUMBERFORMAT_CURRENCY;
1160     sal_uInt8 nParamCount = GetByte();
1161     if ( MustHaveParamCount( nParamCount, 5, 7 ) )
1162     {
1163         double fWert, fRest, fDauer, fAnfang, fEnde, fFaktor, fVdb = 0.0;
1164         sal_Bool bFlag;
1165         if (nParamCount == 7)
1166             bFlag = GetBool();
1167         else
1168             bFlag = sal_False;
1169         if (nParamCount >= 6)
1170             fFaktor = GetDouble();
1171         else
1172             fFaktor = 2.0;
1173         fEnde   = GetDouble();
1174         fAnfang = GetDouble();
1175         fDauer  = GetDouble();
1176         fRest   = GetDouble();
1177         fWert   = GetDouble();
1178         if (fAnfang < 0.0 || fEnde < fAnfang || fEnde > fDauer || fWert < 0.0
1179                           || fRest > fWert || fFaktor <= 0.0)
1180             PushIllegalArgument();
1181         else
1182         {
1183             double fIntStart = ::rtl::math::approxFloor(fAnfang);
1184             double fIntEnd   = ::rtl::math::approxCeil(fEnde);
1185             sal_uLong nLoopStart = (sal_uLong) fIntStart;
1186             sal_uLong nLoopEnd   = (sal_uLong) fIntEnd;
1187 
1188             fVdb = 0.0;
1189             if (bFlag)
1190             {
1191                 for (sal_uLong i = nLoopStart + 1; i <= nLoopEnd; i++)
1192                 {
1193                     double fTerm = ScGetGDA(fWert, fRest, fDauer, (double) i, fFaktor);
1194 
1195                     //  Teilperioden am Anfang / Ende beruecksichtigen:
1196                     if ( i == nLoopStart+1 )
1197                         fTerm *= ( DblMin( fEnde, fIntStart + 1.0 ) - fAnfang );
1198                     else if ( i == nLoopEnd )
1199                         fTerm *= ( fEnde + 1.0 - fIntEnd );
1200 
1201                     fVdb += fTerm;
1202                 }
1203             }
1204             else
1205             {
1206 
1207                 double fDauer1=fDauer;
1208                 double fPart;
1209 
1210                 //@Die Frage aller Fragen: "Ist das hier richtig"
1211                 if(!::rtl::math::approxEqual(fAnfang,::rtl::math::approxFloor(fAnfang)))
1212                 {
1213                     if(fFaktor>1)
1214                     {
1215                         if(fAnfang>fDauer/2 || ::rtl::math::approxEqual(fAnfang,fDauer/2))
1216                         {
1217                             fPart=fAnfang-fDauer/2;
1218                             fAnfang=fDauer/2;
1219                             fEnde-=fPart;
1220                             fDauer1+=1;
1221                         }
1222                     }
1223                 }
1224 
1225                 fWert-=ScInterVDB(fWert,fRest,fDauer,fDauer1,fAnfang,fFaktor);
1226                 fVdb=ScInterVDB(fWert,fRest,fDauer,fDauer-fAnfang,fEnde-fAnfang,fFaktor);
1227             }
1228         }
1229         PushDouble(fVdb);
1230     }
1231 }
1232 
ScLaufz()1233 void ScInterpreter::ScLaufz()
1234 {
1235     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScLaufz" );
1236     if ( MustHaveParamCount( GetByte(), 3 ) )
1237     {
1238         double nZukunft = GetDouble();
1239         double nGegenwart = GetDouble();
1240         double nZins = GetDouble();
1241         PushDouble(log(nZukunft / nGegenwart) / log(1.0 + nZins));
1242     }
1243 }
1244 
ScLIA()1245 void ScInterpreter::ScLIA()
1246 {
1247     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScLIA" );
1248     nFuncFmtType = NUMBERFORMAT_CURRENCY;
1249     if ( MustHaveParamCount( GetByte(), 3 ) )
1250     {
1251         double nDauer = GetDouble();
1252         double nRest = GetDouble();
1253         double nWert = GetDouble();
1254         PushDouble((nWert - nRest) / nDauer);
1255     }
1256 }
1257 
ScGetRmz(double fRate,double fNper,double fPv,double fFv,double fPaytype)1258 double ScInterpreter::ScGetRmz(double fRate, double fNper, double fPv,
1259                        double fFv, double fPaytype)
1260 {
1261     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScGetRmz" );
1262     double fPayment;
1263     if (fRate == 0.0)
1264         fPayment = (fPv + fFv) / fNper;
1265     else
1266     {
1267         if (fPaytype > 0.0) // payment in advance
1268             fPayment = (fFv + fPv * exp( fNper * std::log1p(fRate) ) ) * fRate /
1269                 (std::expm1( (fNper + 1) * std::log1p(fRate) ) - fRate);
1270         else  // payment in arrear
1271             fPayment = (fFv + fPv * exp(fNper * std::log1p(fRate) ) ) * fRate /
1272                 std::expm1( fNper * std::log1p(fRate) );
1273     }
1274     return -fPayment;
1275 }
1276 
ScRMZ()1277 void ScInterpreter::ScRMZ()
1278 {
1279     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScRMZ" );
1280     double nZins, nZzr, nBw, nZw = 0, nFlag = 0;
1281     nFuncFmtType = NUMBERFORMAT_CURRENCY;
1282     sal_uInt8 nParamCount = GetByte();
1283     if ( !MustHaveParamCount( nParamCount, 3, 5 ) )
1284         return;
1285     if (nParamCount == 5)
1286         nFlag = GetDouble();
1287     if (nParamCount >= 4)
1288         nZw   = GetDouble();
1289     nBw   = GetDouble();
1290     nZzr  = GetDouble();
1291     nZins = GetDouble();
1292     PushDouble(ScGetRmz(nZins, nZzr, nBw, nZw, nFlag));
1293 }
1294 
ScZGZ()1295 void ScInterpreter::ScZGZ()
1296 {
1297     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScZGZ" );
1298     nFuncFmtType = NUMBERFORMAT_PERCENT;
1299     if ( MustHaveParamCount( GetByte(), 3 ) )
1300     {
1301         double nZukunftswert = GetDouble();
1302         double nGegenwartswert = GetDouble();
1303         double nZeitraum = GetDouble();
1304         if (nZeitraum <= 0.0)
1305         {
1306             PushIllegalArgument();
1307             return;
1308         }
1309         PushDouble(pow(nZukunftswert / nGegenwartswert, 1.0 / nZeitraum) - 1.0);
1310     }
1311 }
1312 
ScGetZw(double fZins,double fZzr,double fRmz,double fBw,double fF)1313 double ScInterpreter::ScGetZw(double fZins, double fZzr, double fRmz,
1314                               double fBw, double fF)
1315 {
1316     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScGetZw" );
1317     double fZw;
1318     if (fZins == 0.0)
1319         fZw = fBw + fRmz * fZzr;
1320     else
1321     {
1322         double fTerm = pow(1.0 + fZins, fZzr);
1323         if (fF > 0.0)
1324             fZw = fBw * fTerm + fRmz*(1.0 + fZins)*(fTerm - 1.0)/fZins;
1325         else
1326             fZw = fBw * fTerm + fRmz*(fTerm - 1.0)/fZins;
1327     }
1328     return -fZw;
1329 }
1330 
ScZW()1331 void ScInterpreter::ScZW()
1332 {
1333     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScZW" );
1334     double nZins, nZzr, nRmz, nBw = 0, nFlag = 0;
1335     nFuncFmtType = NUMBERFORMAT_CURRENCY;
1336     sal_uInt8 nParamCount = GetByte();
1337     if ( !MustHaveParamCount( nParamCount, 3, 5 ) )
1338         return;
1339     if (nParamCount == 5)
1340         nFlag = GetDouble();
1341     if (nParamCount >= 4)
1342         nBw   = GetDouble();
1343     nRmz  = GetDouble();
1344     nZzr  = GetDouble();
1345     nZins = GetDouble();
1346     PushDouble(ScGetZw(nZins, nZzr, nRmz, nBw, nFlag));
1347 }
1348 
ScZZR()1349 void ScInterpreter::ScZZR()
1350 {
1351     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScZZR" );
1352     double nZins, nRmz, nBw, nZw = 0, nFlag = 0;
1353     sal_uInt8 nParamCount = GetByte();
1354     if ( !MustHaveParamCount( nParamCount, 3, 5 ) )
1355         return;
1356     if (nParamCount == 5)
1357         nFlag = GetDouble();
1358     if (nParamCount >= 4)
1359         nZw   = GetDouble();
1360     nBw   = GetDouble();
1361     nRmz  = GetDouble();
1362     nZins = GetDouble();
1363     if (nZins == 0.0)
1364         PushDouble(-(nBw + nZw)/nRmz);
1365     else if (nFlag > 0.0)
1366         PushDouble(log(-(nZins*nZw-nRmz*(1.0+nZins))/(nZins*nBw+nRmz*(1.0+nZins)))
1367                   /log(1.0+nZins));
1368     else
1369         PushDouble(log(-(nZins*nZw-nRmz)/(nZins*nBw+nRmz))/log(1.0+nZins));
1370 }
1371 
RateIteration(double fNper,double fPayment,double fPv,double fFv,double fPayType,double & fGuess)1372 bool ScInterpreter::RateIteration( double fNper, double fPayment, double fPv,
1373                                    double fFv, double fPayType, double & fGuess )
1374 {
1375     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::RateIteration" );
1376     // See also #i15090#
1377     // Newton-Raphson method: x(i+1) = x(i) - f(x(i)) / f'(x(i))
1378     // This solution handles integer and non-integer values of Nper different.
1379     // If ODFF will constraint Nper to integer, the distinction of cases can be
1380     // removed; only the integer-part is needed then.
1381     bool bValid = true, bFound = false;
1382     double fX, fXnew, fTerm, fTermDerivation;
1383     double fGeoSeries, fGeoSeriesDerivation;
1384     const sal_uInt16 nIterationsMax = 150;
1385     sal_uInt16 nCount = 0;
1386     const double fEpsilonSmall = 1.0E-14;
1387     // convert any fPayType situation to fPayType == zero situation
1388     fFv = fFv - fPayment * fPayType;
1389     fPv = fPv + fPayment * fPayType;
1390     if (fNper == ::rtl::math::round( fNper, 0, rtl_math_RoundingMode_Corrected ))
1391     { // Nper is an integer value
1392         fX = fGuess;
1393         double fPowN, fPowNminus1;  // for (1.0+fX)^Nper and (1.0+fX)^(Nper-1)
1394         while (!bFound && nCount < nIterationsMax)
1395         {
1396             fPowNminus1 = pow( 1.0+fX, fNper-1.0);
1397             fPowN = fPowNminus1 * (1.0+fX);
1398             if (rtl::math::approxEqual( fabs(fX), 0.0))
1399             {
1400                 fGeoSeries = fNper;
1401                 fGeoSeriesDerivation = fNper * (fNper-1.0)/2.0;
1402             }
1403             else
1404             {
1405                 fGeoSeries = (fPowN-1.0)/fX;
1406                 fGeoSeriesDerivation = fNper * fPowNminus1 / fX - fGeoSeries / fX;
1407             }
1408             fTerm = fFv + fPv *fPowN+ fPayment * fGeoSeries;
1409             fTermDerivation = fPv * fNper * fPowNminus1 + fPayment * fGeoSeriesDerivation;
1410             if (fabs(fTerm) < fEpsilonSmall)
1411                 bFound = true;  // will catch root which is at an extreme
1412             else
1413             {
1414                 if (rtl::math::approxEqual( fabs(fTermDerivation), 0.0))
1415                     fXnew = fX + 1.1 * SCdEpsilon;  // move away from zero slope
1416                 else
1417                     fXnew = fX - fTerm / fTermDerivation;
1418             nCount++;
1419             // more accuracy not possible in oscillating cases
1420             bFound = (fabs(fXnew - fX) < SCdEpsilon);
1421             fX = fXnew;
1422             }
1423         }
1424         // Gnumeric returns roots < -1, Excel gives an error in that cases,
1425         // ODFF says nothing about it. Enable the statement, if you want Excel's
1426         // behavior
1427         //bValid =(fX >=-1.0);
1428     }
1429     else
1430     { // Nper is not an integer value.
1431         fX = (fGuess < -1.0) ? -1.0 : fGuess;   // start with a valid fX
1432         while (bValid && !bFound && nCount < nIterationsMax)
1433         {
1434             if (rtl::math::approxEqual( fabs(fX), 0.0))
1435             {
1436                 fGeoSeries = fNper;
1437                 fGeoSeriesDerivation = fNper * (fNper-1.0)/2.0;
1438             }
1439             else
1440             {
1441                 fGeoSeries = (pow( 1.0+fX, fNper) - 1.0) / fX;
1442                 fGeoSeriesDerivation = fNper * pow( 1.0+fX, fNper-1.0) / fX - fGeoSeries / fX;
1443             }
1444             fTerm = fFv + fPv *pow(1.0 + fX,fNper)+ fPayment * fGeoSeries;
1445             fTermDerivation = fPv * fNper * pow( 1.0+fX, fNper-1.0) + fPayment * fGeoSeriesDerivation;
1446             if (fabs(fTerm) < fEpsilonSmall)
1447                 bFound = true;  // will catch root which is at an extreme
1448             else
1449             {
1450                 if (rtl::math::approxEqual( fabs(fTermDerivation), 0.0))
1451                     fXnew = fX + 1.1 * SCdEpsilon;  // move away from zero slope
1452                 else
1453                     fXnew = fX - fTerm / fTermDerivation;
1454             nCount++;
1455              // more accuracy not possible in oscillating cases
1456             bFound = (fabs(fXnew - fX) < SCdEpsilon);
1457             fX = fXnew;
1458             bValid = (fX >= -1.0);  // otherwise pow(1.0+fX,fNper) will fail
1459             }
1460         }
1461     }
1462     fGuess = fX;    // return approximate root
1463     return bValid && bFound;
1464 }
1465 
1466 // In Calc UI it is the function RATE(Nper;Pmt;Pv;Fv;Type;Guess)
ScZins()1467 void ScInterpreter::ScZins()
1468 {
1469     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScZins" );
1470     double fPv, fPayment, fNper;
1471     // defaults for missing arguments, see ODFF spec
1472     double fFv = 0, fPayType = 0, fGuess = 0.1;
1473     bool bValid = true;
1474     nFuncFmtType = NUMBERFORMAT_PERCENT;
1475     sal_uInt8 nParamCount = GetByte();
1476     if ( !MustHaveParamCount( nParamCount, 3, 6 ) )
1477         return;
1478     if (nParamCount == 6)
1479         fGuess = GetDouble();
1480     if (nParamCount >= 5)
1481         fPayType = GetDouble();
1482     if (nParamCount >= 4)
1483         fFv = GetDouble();
1484     fPv = GetDouble();
1485     fPayment = GetDouble();
1486     fNper = GetDouble();
1487     if (fNper <= 0.0) // constraint from ODFF spec
1488     {
1489         PushIllegalArgument();
1490         return;
1491     }
1492     // other values for fPayType might be meaningful,
1493     // ODFF spec is not clear yet, enable statement if you want only 0 and 1
1494     //if (fPayType != 0.0) fPayType = 1.0;
1495     bValid = RateIteration(fNper, fPayment, fPv, fFv, fPayType, fGuess);
1496     if (!bValid)
1497         SetError(errNoConvergence);
1498     PushDouble(fGuess);
1499 }
1500 
ScGetZinsZ(double fZins,double fZr,double fZzr,double fBw,double fZw,double fF,double & fRmz)1501 double ScInterpreter::ScGetZinsZ(double fZins, double fZr, double fZzr, double fBw,
1502                                  double fZw, double fF, double& fRmz)
1503 {
1504     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScGetZinsZ" );
1505     fRmz = ScGetRmz(fZins, fZzr, fBw, fZw, fF);     // fuer kapz auch bei fZr == 1
1506     double fZinsZ;
1507     nFuncFmtType = NUMBERFORMAT_CURRENCY;
1508     if (fZr == 1.0)
1509     {
1510         if (fF > 0.0)
1511             fZinsZ = 0.0;
1512         else
1513             fZinsZ = -fBw;
1514     }
1515     else
1516     {
1517         if (fF > 0.0)
1518             fZinsZ = ScGetZw(fZins, fZr-2.0, fRmz, fBw, 1.0) - fRmz;
1519         else
1520             fZinsZ = ScGetZw(fZins, fZr-1.0, fRmz, fBw, 0.0);
1521     }
1522     return fZinsZ * fZins;
1523 }
1524 
ScZinsZ()1525 void ScInterpreter::ScZinsZ()
1526 {
1527     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScZinsZ" );
1528     double nZins, nZr, nRmz, nZzr, nBw, nZw = 0, nFlag = 0;
1529     nFuncFmtType = NUMBERFORMAT_CURRENCY;
1530     sal_uInt8 nParamCount = GetByte();
1531     if ( !MustHaveParamCount( nParamCount, 4, 6 ) )
1532         return;
1533     if (nParamCount == 6)
1534         nFlag = GetDouble();
1535     if (nParamCount >= 5)
1536         nZw   = GetDouble();
1537     nBw   = GetDouble();
1538     nZzr  = GetDouble();
1539     nZr   = GetDouble();
1540     nZins = GetDouble();
1541     if (nZr < 1.0 || nZr > nZzr)
1542         PushIllegalArgument();
1543     else
1544         PushDouble(ScGetZinsZ(nZins, nZr, nZzr, nBw, nZw, nFlag, nRmz));
1545 }
1546 
ScKapz()1547 void ScInterpreter::ScKapz()
1548 {
1549     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScKapz" );
1550     double nZins, nZr, nZzr, nBw, nZw = 0, nFlag = 0, nRmz, nZinsz;
1551     nFuncFmtType = NUMBERFORMAT_CURRENCY;
1552     sal_uInt8 nParamCount = GetByte();
1553     if ( !MustHaveParamCount( nParamCount, 4, 6 ) )
1554         return;
1555     if (nParamCount == 6)
1556         nFlag = GetDouble();
1557     if (nParamCount >= 5)
1558         nZw   = GetDouble();
1559     nBw   = GetDouble();
1560     nZzr  = GetDouble();
1561     nZr   = GetDouble();
1562     nZins = GetDouble();
1563     if (nZr < 1.0 || nZr > nZzr)
1564         PushIllegalArgument();
1565     else
1566     {
1567         nZinsz = ScGetZinsZ(nZins, nZr, nZzr, nBw, nZw, nFlag, nRmz);
1568         PushDouble(nRmz - nZinsz);
1569     }
1570 }
1571 
ScKumZinsZ()1572 void ScInterpreter::ScKumZinsZ()
1573 {
1574     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScKumZinsZ" );
1575     nFuncFmtType = NUMBERFORMAT_CURRENCY;
1576     if ( MustHaveParamCount( GetByte(), 6 ) )
1577     {
1578         double fZins, fZzr, fBw, fAnfang, fEnde, fF, fRmz, fZinsZ;
1579         fF      = GetDouble();
1580         fEnde   = ::rtl::math::approxFloor(GetDouble());
1581         fAnfang = ::rtl::math::approxFloor(GetDouble());
1582         fBw     = GetDouble();
1583         fZzr    = GetDouble();
1584         fZins   = GetDouble();
1585         if (fAnfang < 1.0 || fEnde < fAnfang || fZins <= 0.0 ||
1586             fEnde > fZzr  || fZzr <= 0.0 || fBw <= 0.0)
1587             PushIllegalArgument();
1588         else
1589         {
1590             sal_uLong nAnfang = (sal_uLong) fAnfang;
1591             sal_uLong nEnde = (sal_uLong) fEnde ;
1592             fRmz = ScGetRmz(fZins, fZzr, fBw, 0.0, fF);
1593             fZinsZ = 0.0;
1594             if (nAnfang == 1)
1595             {
1596                 if (fF <= 0.0)
1597                     fZinsZ = -fBw;
1598                 nAnfang++;
1599             }
1600             for (sal_uLong i = nAnfang; i <= nEnde; i++)
1601             {
1602                 if (fF > 0.0)
1603                     fZinsZ += ScGetZw(fZins, (double)(i-2), fRmz, fBw, 1.0) - fRmz;
1604                 else
1605                     fZinsZ += ScGetZw(fZins, (double)(i-1), fRmz, fBw, 0.0);
1606             }
1607             fZinsZ *= fZins;
1608             PushDouble(fZinsZ);
1609         }
1610     }
1611 }
1612 
ScKumKapZ()1613 void ScInterpreter::ScKumKapZ()
1614 {
1615     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScKumKapZ" );
1616     nFuncFmtType = NUMBERFORMAT_CURRENCY;
1617     if ( MustHaveParamCount( GetByte(), 6 ) )
1618     {
1619         double fZins, fZzr, fBw, fAnfang, fEnde, fF, fRmz, fKapZ;
1620         fF      = GetDouble();
1621         fEnde   = ::rtl::math::approxFloor(GetDouble());
1622         fAnfang = ::rtl::math::approxFloor(GetDouble());
1623         fBw     = GetDouble();
1624         fZzr    = GetDouble();
1625         fZins   = GetDouble();
1626         if (fAnfang < 1.0 || fEnde < fAnfang || fZins <= 0.0 ||
1627             fEnde > fZzr  || fZzr <= 0.0 || fBw <= 0.0)
1628             PushIllegalArgument();
1629         else
1630         {
1631             fRmz = ScGetRmz(fZins, fZzr, fBw, 0.0, fF);
1632             fKapZ = 0.0;
1633             sal_uLong nAnfang = (sal_uLong) fAnfang;
1634             sal_uLong nEnde = (sal_uLong) fEnde;
1635             if (nAnfang == 1)
1636             {
1637                 if (fF <= 0.0)
1638                     fKapZ = fRmz + fBw * fZins;
1639                 else
1640                     fKapZ = fRmz;
1641                 nAnfang++;
1642             }
1643             for (sal_uLong i = nAnfang; i <= nEnde; i++)
1644             {
1645                 if (fF > 0.0)
1646                     fKapZ += fRmz - (ScGetZw(fZins, (double)(i-2), fRmz, fBw, 1.0) - fRmz) * fZins;
1647                 else
1648                     fKapZ += fRmz - ScGetZw(fZins, (double)(i-1), fRmz, fBw, 0.0) * fZins;
1649             }
1650             PushDouble(fKapZ);
1651         }
1652     }
1653 }
1654 
ScEffektiv()1655 void ScInterpreter::ScEffektiv()
1656 {
1657     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScEffektiv" );
1658     nFuncFmtType = NUMBERFORMAT_PERCENT;
1659     if ( MustHaveParamCount( GetByte(), 2 ) )
1660     {
1661         double fPerioden = GetDouble();
1662         double fNominal = GetDouble();
1663         if (fPerioden < 1.0 || fNominal <= 0.0)
1664             PushIllegalArgument();
1665         else
1666         {
1667             fPerioden = ::rtl::math::approxFloor(fPerioden);
1668             PushDouble(pow(1.0 + fNominal/fPerioden, fPerioden) - 1.0);
1669         }
1670     }
1671 }
1672 
ScNominal()1673 void ScInterpreter::ScNominal()
1674 {
1675     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScNominal" );
1676     nFuncFmtType = NUMBERFORMAT_PERCENT;
1677     if ( MustHaveParamCount( GetByte(), 2 ) )
1678     {
1679         double fPerioden = GetDouble();
1680         double fEffektiv = GetDouble();
1681         if (fPerioden < 1.0 || fEffektiv <= 0.0)
1682             PushIllegalArgument();
1683         else
1684         {
1685             fPerioden = ::rtl::math::approxFloor(fPerioden);
1686             PushDouble( (pow(fEffektiv + 1.0, 1.0 / fPerioden) - 1.0) * fPerioden );
1687         }
1688     }
1689 }
1690 
ScMod()1691 void ScInterpreter::ScMod()
1692 {
1693     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScMod" );
1694     if ( MustHaveParamCount( GetByte(), 2 ) )
1695     {
1696         double fVal2 = GetDouble(); // Denominator
1697         double fVal1 = GetDouble(); // Numerator
1698         if (fVal2 == floor(fVal2))  // a pure integral number stored in double
1699         {
1700             double fResult = fmod(fVal1,fVal2);
1701             if ( (fResult != 0.0) &&
1702                 ((fVal1 > 0.0 && fVal2 < 0.0) || (fVal1 < 0.0 && fVal2 > 0.0)))
1703                 fResult += fVal2 ;
1704             PushDouble( fResult );
1705         }
1706         else
1707         {
1708             PushDouble( ::rtl::math::approxSub( fVal1,
1709                     ::rtl::math::approxFloor(fVal1 / fVal2) * fVal2));
1710         }
1711     }
1712 }
1713 
1714 /** (Goal Seek) Find a value of x that is a root of f(x)
1715 
1716     This function is used internally for the goal seek operation.  It uses the
1717     Regula Falsi (aka false position) algorithm to find a root of f(x).  The
1718     start value and the target value are to be given by the user in the
1719     goal seek dialog.  The f(x) in this case is defined as the formula in the
1720     formula cell minus target value.  This function may also perform additional
1721     search in the horizontal directions when the f(x) is discrete in order to
1722     ensure a non-zero slope necessary for deriving a subsequent x that is
1723     reasonably close to the root of interest.
1724 
1725     @change 24.10.2004 by Kohei Yoshida (kohei@openoffice.org)
1726 
1727     @see #i28955#
1728 */
ScBackSolver()1729 void ScInterpreter::ScBackSolver()
1730 {
1731     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScBackSolver" );
1732     if ( MustHaveParamCount( GetByte(), 3 ) )
1733     {
1734         sal_Bool bDoneIteration = sal_False;
1735         ScAddress aValueAdr, aFormulaAdr;
1736         double fTargetVal = GetDouble();
1737         PopSingleRef( aFormulaAdr );
1738         PopSingleRef( aValueAdr );
1739 
1740         if (nGlobalError == 0)
1741         {
1742             ScBaseCell* pVCell = GetCell( aValueAdr );
1743             // CELLTYPE_NOTE: kein Value aber von Formel referiert
1744             sal_Bool bTempCell = (!pVCell || pVCell->GetCellType() == CELLTYPE_NOTE);
1745             ScBaseCell* pFCell = GetCell( aFormulaAdr );
1746 
1747             if ( ((pVCell && pVCell->GetCellType() == CELLTYPE_VALUE) || bTempCell)
1748                 && pFCell && pFCell->GetCellType() == CELLTYPE_FORMULA )
1749             {
1750                 ScRange aVRange( aValueAdr, aValueAdr );    // for SetDirty
1751                 double fSaveVal; // Original value to be restored later if necessary
1752                 ScPostIt* pNote = 0;
1753 
1754                 if ( bTempCell )
1755                 {
1756                     pNote = pVCell ? pVCell->ReleaseNote() : 0;
1757                     fSaveVal = 0.0;
1758                     pVCell = new ScValueCell( fSaveVal );
1759                     pDok->PutCell( aValueAdr, pVCell );
1760                 }
1761                 else
1762                     fSaveVal = GetCellValue( aValueAdr, pVCell );
1763 
1764                 const sal_uInt16 nMaxIter = 100;
1765                 const double fEps = 1E-10;
1766                 const double fDelta = 1E-6;
1767 
1768                 double fBestX, fXPrev;
1769                 double fBestF, fFPrev;
1770                 fBestX = fXPrev = fSaveVal;
1771 
1772                 ScFormulaCell* pFormula = (ScFormulaCell*) pFCell;
1773                 ScValueCell* pValue = (ScValueCell*) pVCell;
1774 
1775                 pFormula->Interpret();
1776                 sal_Bool bError = ( pFormula->GetErrCode() != 0 );
1777                 // bError always corresponds with fF
1778 
1779                 fFPrev = pFormula->GetValue() - fTargetVal;
1780 
1781                 fBestF = fabs( fFPrev );
1782                 if ( fBestF < fDelta )
1783                     bDoneIteration = sal_True;
1784 
1785                 double fX = fXPrev + fEps;
1786                 double fF = fFPrev;
1787                 double fSlope;
1788 
1789                 sal_uInt16 nIter = 0;
1790 
1791                 sal_Bool bHorMoveError = sal_False;
1792                                                 // Nach der Regula Falsi Methode
1793                 while ( !bDoneIteration && ( nIter++ < nMaxIter ) )
1794                 {
1795                     pValue->SetValue( fX );
1796                     pDok->SetDirty( aVRange );
1797                     pFormula->Interpret();
1798                     bError = ( pFormula->GetErrCode() != 0 );
1799                     fF = pFormula->GetValue() - fTargetVal;
1800 
1801                     if ( fF == fFPrev && !bError )
1802                     {
1803                         // HORIZONTAL SEARCH: Keep moving x in both directions until the f(x)
1804                         // becomes different from the previous f(x).  This routine is needed
1805                         // when a given function is discrete, in which case the resulting slope
1806                         // may become zero which ultimately causes the goal seek operation
1807                         // to fail. #i28955#
1808 
1809                         sal_uInt16 nHorIter = 0;
1810                         const double fHorStepAngle = 5.0;
1811                         const double fHorMaxAngle = 80.0;
1812                         int nHorMaxIter = static_cast<int>( fHorMaxAngle / fHorStepAngle );
1813                         sal_Bool bDoneHorMove = sal_False;
1814 
1815                         while ( !bDoneHorMove && !bHorMoveError && nHorIter++ < nHorMaxIter )
1816                         {
1817                             double fHorAngle = fHorStepAngle * static_cast<double>( nHorIter );
1818                             double fHorTangent = ::rtl::math::tan( fHorAngle * F_PI / 180 );
1819 
1820                             sal_uInt16 nIdx = 0;
1821                             while( nIdx++ < 2 && !bDoneHorMove )
1822                             {
1823                                 double fHorX;
1824                                 if ( nIdx == 1 )
1825                                     fHorX = fX + fabs(fF)*fHorTangent;
1826                                 else
1827                                     fHorX = fX - fabs(fF)*fHorTangent;
1828 
1829                                 pValue->SetValue( fHorX );
1830                                 pDok->SetDirty( aVRange );
1831                                 pFormula->Interpret();
1832                                 bHorMoveError = ( pFormula->GetErrCode() != 0 );
1833                                 if ( bHorMoveError )
1834                                     break;
1835 
1836                                 fF = pFormula->GetValue() - fTargetVal;
1837                                 if ( fF != fFPrev )
1838                                 {
1839                                     fX = fHorX;
1840                                     bDoneHorMove = sal_True;
1841                                 }
1842                             }
1843                         }
1844                         if ( !bDoneHorMove )
1845                             bHorMoveError = sal_True;
1846                     }
1847 
1848                     if ( bError )
1849                     {
1850                         // move closer to last valid value (fXPrev), keep fXPrev & fFPrev
1851                         double fDiff = ( fXPrev - fX ) / 2;
1852                         if (fabs(fDiff) < fEps)
1853                             fDiff = (fDiff < 0.0) ? - fEps : fEps;
1854                         fX += fDiff;
1855                     }
1856                     else if ( bHorMoveError )
1857                         break;
1858                     else if ( fabs(fF) < fDelta )
1859                     {
1860                         // converged to root
1861                         fBestX = fX;
1862                         bDoneIteration = sal_True;
1863                     }
1864                     else
1865                     {
1866                         if ( fabs(fF) + fDelta < fBestF )
1867                         {
1868                             fBestX = fX;
1869                             fBestF = fabs(fF);
1870                         }
1871 
1872                         if ( ( fXPrev - fX ) != 0 )
1873                         {
1874                             fSlope = ( fFPrev - fF ) / ( fXPrev - fX );
1875                             if ( fabs( fSlope ) < fEps )
1876                                 fSlope = fSlope < 0.0 ? -fEps : fEps;
1877                         }
1878                         else
1879                             fSlope = fEps;
1880 
1881                         fXPrev = fX;
1882                         fFPrev = fF;
1883                         fX = fX - ( fF / fSlope );
1884                     }
1885                 }
1886 
1887                 // Try a nice rounded input value if possible.
1888                 const double fNiceDelta = (bDoneIteration && fabs(fBestX) >= 1e-3 ? 1e-3 : fDelta);
1889                 double nX = ::rtl::math::approxFloor((fBestX / fNiceDelta) + 0.5) * fNiceDelta;
1890 //                double nX = ::rtl::math::approxFloor((fBestX / fDelta) + 0.5) * fDelta;
1891 
1892                 if ( bDoneIteration )
1893                 {
1894                     pValue->SetValue( nX );
1895                     pDok->SetDirty( aVRange );
1896                     pFormula->Interpret();
1897                     if ( fabs( pFormula->GetValue() - fTargetVal ) > fabs( fF ) )
1898                         nX = fBestX;
1899                 }
1900                 else if ( bError || bHorMoveError )
1901                 {
1902                     nX = fBestX;
1903                 }
1904                 if ( bTempCell )
1905                 {
1906                     pVCell = pNote ? new ScNoteCell( pNote ) : 0;
1907                     pDok->PutCell( aValueAdr, pVCell );
1908                 }
1909                 else
1910                     pValue->SetValue( fSaveVal );
1911                 pDok->SetDirty( aVRange );
1912                 pFormula->Interpret();
1913                 if ( !bDoneIteration )
1914                     SetError(NOTAVAILABLE);
1915                 PushDouble(nX);
1916             }
1917             else
1918             {
1919                 if ( !bDoneIteration )
1920                     SetError(NOTAVAILABLE);
1921                 PushInt(0);         // falsche Zelltypen
1922             }
1923         }
1924         else
1925         {
1926             if ( !bDoneIteration )
1927                 SetError(NOTAVAILABLE);
1928             PushInt(0);             // nGlobalError
1929         }
1930     }
1931 }
1932 
ScIntersect()1933 void ScInterpreter::ScIntersect()
1934 {
1935     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScIntersect" );
1936     formula::FormulaTokenRef p2nd = PopToken();
1937     formula::FormulaTokenRef p1st = PopToken();
1938 
1939     if (nGlobalError || !p2nd || !p1st)
1940     {
1941         PushIllegalArgument();
1942         return;
1943     } // if (nGlobalError || !xT2 || !xT1)
1944 
1945     StackVar sv1 = p1st->GetType();
1946     StackVar sv2 = p2nd->GetType();
1947     if ((sv1 != svSingleRef && sv1 != svDoubleRef && sv1 != svRefList) ||
1948         (sv2 != svSingleRef && sv2 != svDoubleRef && sv2 != svRefList))
1949     {
1950         PushIllegalArgument();
1951         return;
1952     }
1953 
1954     ScToken* x1 = static_cast<ScToken*>(p1st.get());
1955     ScToken* x2 = static_cast<ScToken*>(p2nd.get());
1956     if (sv1 == svRefList || sv2 == svRefList)
1957     {
1958         // Now this is a bit nasty but it simplifies things, and having
1959         // intersections with lists isn't too common, if at all..
1960         // Convert a reference to list.
1961         ScToken* xt[2] = { x1, x2 };
1962         StackVar sv[2] = { sv1, sv2 };
1963         for (size_t i=0; i<2; ++i)
1964         {
1965             if (sv[i] == svSingleRef)
1966             {
1967                 ScComplexRefData aRef;
1968                 aRef.Ref1 = aRef.Ref2 = xt[i]->GetSingleRef();
1969                 xt[i] = new ScRefListToken;
1970                 xt[i]->GetRefList()->push_back( aRef);
1971             }
1972             else if (sv[i] == svDoubleRef)
1973             {
1974                 ScComplexRefData aRef = xt[i]->GetDoubleRef();
1975                 xt[i] = new ScRefListToken;
1976                 xt[i]->GetRefList()->push_back( aRef);
1977             }
1978         }
1979         x1 = xt[0], x2 = xt[1];
1980 
1981         x1->CalcAbsIfRel( aPos);
1982         x2->CalcAbsIfRel( aPos);
1983         ScTokenRef xRes = new ScRefListToken;
1984         ScRefList* pRefList = xRes->GetRefList();
1985         ScRefList::const_iterator end1( x1->GetRefList()->end());
1986         ScRefList::const_iterator end2( x2->GetRefList()->end());
1987         for (ScRefList::const_iterator it1( x1->GetRefList()->begin());
1988                 it1 != end1; ++it1)
1989         {
1990             const ScSingleRefData& r11 = (*it1).Ref1;
1991             const ScSingleRefData& r12 = (*it1).Ref2;
1992             for (ScRefList::const_iterator it2( x2->GetRefList()->begin());
1993                     it2 != end2; ++it2)
1994             {
1995                 const ScSingleRefData& r21 = (*it2).Ref1;
1996                 const ScSingleRefData& r22 = (*it2).Ref2;
1997                 SCCOL nCol1 = ::std::max( r11.nCol, r21.nCol);
1998                 SCROW nRow1 = ::std::max( r11.nRow, r21.nRow);
1999                 SCTAB nTab1 = ::std::max( r11.nTab, r21.nTab);
2000                 SCCOL nCol2 = ::std::min( r12.nCol, r22.nCol);
2001                 SCROW nRow2 = ::std::min( r12.nRow, r22.nRow);
2002                 SCTAB nTab2 = ::std::min( r12.nTab, r22.nTab);
2003                 if (nCol2 < nCol1 || nRow2 < nRow1 || nTab2 < nTab1)
2004                     ;   // nothing
2005                 else
2006                 {
2007                     ScComplexRefData aRef;
2008                     aRef.InitRange( nCol1, nRow1, nTab1, nCol2, nRow2, nTab2);
2009                     pRefList->push_back( aRef);
2010                 }
2011             }
2012         }
2013         size_t n = pRefList->size();
2014         if (!n)
2015             PushError( errNoRef);
2016         else if (n == 1)
2017         {
2018             const ScComplexRefData& rRef = (*pRefList)[0];
2019             if (rRef.Ref1 == rRef.Ref2)
2020                 PushTempToken( new ScSingleRefToken( rRef.Ref1));
2021             else
2022                 PushTempToken( new ScDoubleRefToken( rRef));
2023         }
2024         else
2025             PushTempToken( xRes);
2026     }
2027     else
2028     {
2029         ScToken* pt[2] = { x1, x2 };
2030         StackVar sv[2] = { sv1, sv2 };
2031         SCCOL nC1[2], nC2[2];
2032         SCROW nR1[2], nR2[2];
2033         SCTAB nT1[2], nT2[2];
2034         for (size_t i=0; i<2; ++i)
2035         {
2036             switch (sv[i])
2037             {
2038                 case svSingleRef:
2039                 case svDoubleRef:
2040                     pt[i]->CalcAbsIfRel( aPos);
2041                     {
2042                         const ScSingleRefData& r = pt[i]->GetSingleRef();
2043                         nC1[i] = r.nCol;
2044                         nR1[i] = r.nRow;
2045                         nT1[i] = r.nTab;
2046                     }
2047                     if (sv[i] == svDoubleRef)
2048                     {
2049                         const ScSingleRefData& r = pt[i]->GetSingleRef2();
2050                         nC2[i] = r.nCol;
2051                         nR2[i] = r.nRow;
2052                         nT2[i] = r.nTab;
2053                     }
2054                     else
2055                     {
2056                         nC2[i] = nC1[i];
2057                         nR2[i] = nR1[i];
2058                         nT2[i] = nT1[i];
2059                     }
2060                     break;
2061                 default:
2062                     ;   // nothing, prevent compiler warning
2063             }
2064         }
2065         SCCOL nCol1 = ::std::max( nC1[0], nC1[1]);
2066         SCROW nRow1 = ::std::max( nR1[0], nR1[1]);
2067         SCTAB nTab1 = ::std::max( nT1[0], nT1[1]);
2068         SCCOL nCol2 = ::std::min( nC2[0], nC2[1]);
2069         SCROW nRow2 = ::std::min( nR2[0], nR2[1]);
2070         SCTAB nTab2 = ::std::min( nT2[0], nT2[1]);
2071         if (nCol2 < nCol1 || nRow2 < nRow1 || nTab2 < nTab1)
2072             PushError( errNoRef);
2073         else if (nCol2 == nCol1 && nRow2 == nRow1 && nTab2 == nTab1)
2074             PushSingleRef( nCol1, nRow1, nTab1);
2075         else
2076             PushDoubleRef( nCol1, nRow1, nTab1, nCol2, nRow2, nTab2);
2077     }
2078 }
2079 
2080 
ScRangeFunc()2081 void ScInterpreter::ScRangeFunc()
2082 {
2083     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScRangeFunc" );
2084     formula::FormulaTokenRef x2 = PopToken();
2085     formula::FormulaTokenRef x1 = PopToken();
2086 
2087     if (nGlobalError || !x2 || !x1)
2088     {
2089         PushIllegalArgument();
2090         return;
2091     } // if (nGlobalError || !xT2 || !xT1)
2092     FormulaTokenRef xRes = ScToken::ExtendRangeReference( *x1, *x2, aPos, false);
2093     if (!xRes)
2094         PushIllegalArgument();
2095     else
2096         PushTempToken( xRes);
2097 }
2098 
2099 
ScUnionFunc()2100 void ScInterpreter::ScUnionFunc()
2101 {
2102     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScUnionFunc" );
2103     formula::FormulaTokenRef p2nd = PopToken();
2104     formula::FormulaTokenRef p1st = PopToken();
2105 
2106     if (nGlobalError || !p2nd || !p1st)
2107     {
2108         PushIllegalArgument();
2109         return;
2110     } // if (nGlobalError || !xT2 || !xT1)
2111 
2112     StackVar sv1 = p1st->GetType();
2113     StackVar sv2 = p2nd->GetType();
2114     if ((sv1 != svSingleRef && sv1 != svDoubleRef && sv1 != svRefList) ||
2115         (sv2 != svSingleRef && sv2 != svDoubleRef && sv2 != svRefList))
2116     {
2117         PushIllegalArgument();
2118         return;
2119     }
2120 
2121     ScToken* x1 = static_cast<ScToken*>(p1st.get());
2122     ScToken* x2 = static_cast<ScToken*>(p2nd.get());
2123 
2124 
2125     ScTokenRef xRes;
2126     // Append to an existing RefList if there is one.
2127     if (sv1 == svRefList)
2128     {
2129         xRes = x1;
2130         sv1 = svUnknown;    // mark as handled
2131     }
2132     else if (sv2 == svRefList)
2133     {
2134         xRes = x2;
2135         sv2 = svUnknown;    // mark as handled
2136     }
2137     else
2138         xRes = new ScRefListToken;
2139     ScRefList* pRes = xRes->GetRefList();
2140     ScToken* pt[2] = { x1, x2 };
2141     StackVar sv[2] = { sv1, sv2 };
2142     for (size_t i=0; i<2; ++i)
2143     {
2144         if (pt[i] == xRes)
2145             continue;
2146         switch (sv[i])
2147         {
2148             case svSingleRef:
2149                 {
2150                     ScComplexRefData aRef;
2151                     aRef.Ref1 = aRef.Ref2 = pt[i]->GetSingleRef();
2152                     pRes->push_back( aRef);
2153                 }
2154                 break;
2155             case svDoubleRef:
2156                 pRes->push_back( pt[i]->GetDoubleRef());
2157                 break;
2158             case svRefList:
2159                 {
2160                     const ScRefList* p = pt[i]->GetRefList();
2161                     ScRefList::const_iterator it( p->begin());
2162                     ScRefList::const_iterator end( p->end());
2163                     for ( ; it != end; ++it)
2164                     {
2165                         pRes->push_back( *it);
2166                     }
2167                 }
2168                 break;
2169             default:
2170                 ;   // nothing, prevent compiler warning
2171         }
2172     }
2173     ValidateRef( *pRes);    // set #REF! if needed
2174     PushTempToken( xRes);
2175 }
2176 
2177 
ScCurrent()2178 void ScInterpreter::ScCurrent()
2179 {
2180     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScCurrent" );
2181     FormulaTokenRef xTok( PopToken());
2182     if (xTok)
2183     {
2184         PushTempToken( xTok);
2185         PushTempToken( xTok);
2186     }
2187     else
2188         PushError( errUnknownStackVariable);
2189 }
2190 
ScStyle()2191 void ScInterpreter::ScStyle()
2192 {
2193     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScStyle" );
2194     sal_uInt8 nParamCount = GetByte();
2195     if (nParamCount >= 1 && nParamCount <= 3)
2196     {
2197         String aStyle2;                             // Vorlage nach Timer
2198         if (nParamCount >= 3)
2199             aStyle2 = GetString();
2200         long nTimeOut = 0;                          // Timeout
2201         if (nParamCount >= 2)
2202             nTimeOut = (long)(GetDouble()*1000.0);
2203         String aStyle1 = GetString();               // Vorlage für sofort
2204 
2205         if (nTimeOut < 0)
2206             nTimeOut = 0;
2207 
2208         //
2209         //  Request ausführen, um Vorlage anzuwenden
2210         //
2211 
2212         if ( !pDok->IsClipOrUndo() )
2213         {
2214             SfxObjectShell* pShell = pDok->GetDocumentShell();
2215             if (pShell)
2216             {
2217                 //! notify object shell directly
2218 
2219                 ScRange aRange(aPos);
2220                 ScAutoStyleHint aHint( aRange, aStyle1, nTimeOut, aStyle2 );
2221                 pShell->Broadcast( aHint );
2222             }
2223         }
2224 
2225         PushDouble(0.0);
2226     }
2227     else
2228         PushIllegalParameter();
2229 }
2230 
lcl_GetDdeLink(sfx2::LinkManager * pLinkMgr,const String & rA,const String & rT,const String & rI,sal_uInt8 nM)2231 ScDdeLink* lcl_GetDdeLink( sfx2::LinkManager* pLinkMgr,
2232                                 const String& rA, const String& rT, const String& rI, sal_uInt8 nM )
2233 {
2234     sal_uInt16 nCount = pLinkMgr->GetLinks().Count();
2235     for (sal_uInt16 i=0; i<nCount; i++ )
2236     {
2237         ::sfx2::SvBaseLink* pBase = *pLinkMgr->GetLinks()[i];
2238         if (pBase->ISA(ScDdeLink))
2239         {
2240             ScDdeLink* pLink = (ScDdeLink*)pBase;
2241             if ( pLink->GetAppl() == rA &&
2242                  pLink->GetTopic() == rT &&
2243                  pLink->GetItem() == rI &&
2244                  pLink->GetMode() == nM )
2245                 return pLink;
2246         }
2247     }
2248 
2249     return NULL;
2250 }
2251 
ScDde()2252 void ScInterpreter::ScDde()
2253 {
2254     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScDde" );
2255     //  Applikation, Datei, Bereich
2256     //  Application, Topic, Item
2257 
2258     sal_uInt8 nParamCount = GetByte();
2259     if ( MustHaveParamCount( nParamCount, 3, 4 ) )
2260     {
2261         sal_uInt8 nMode = SC_DDE_DEFAULT;
2262         if (nParamCount == 4)
2263             nMode = (sal_uInt8) ::rtl::math::approxFloor(GetDouble());
2264         String aItem  = GetString();
2265         String aTopic = GetString();
2266         String aAppl  = GetString();
2267 
2268         if (nMode > SC_DDE_TEXT)
2269             nMode = SC_DDE_DEFAULT;
2270 
2271         //  temporary documents (ScFunctionAccess) have no DocShell
2272         //  and no LinkManager -> abort
2273 
2274         sfx2::LinkManager* pLinkMgr = pDok->GetLinkManager();
2275         if (!pLinkMgr)
2276         {
2277             PushNoValue();
2278             return;
2279         }
2280 
2281             //  Nach dem Laden muss neu interpretiert werden (Verknüpfungen aufbauen)
2282 
2283         if ( pMyFormulaCell->GetCode()->IsRecalcModeNormal() )
2284             pMyFormulaCell->GetCode()->SetRecalcModeOnLoad();
2285 
2286             //  solange der Link nicht ausgewertet ist, Idle abklemmen
2287             //  (um zirkuläre Referenzen zu vermeiden)
2288 
2289         sal_Bool bOldDis = pDok->IsIdleDisabled();
2290         pDok->DisableIdle( sal_True );
2291 
2292             //  Link-Objekt holen / anlegen
2293 
2294         ScDdeLink* pLink = lcl_GetDdeLink( pLinkMgr, aAppl, aTopic, aItem, nMode );
2295 
2296         //! Dde-Links (zusaetzlich) effizienter am Dokument speichern !!!!!
2297         //      ScDdeLink* pLink = pDok->GetDdeLink( aAppl, aTopic, aItem );
2298 
2299         sal_Bool bWasError = ( pMyFormulaCell->GetRawError() != 0 );
2300 
2301         if (!pLink)
2302         {
2303             pLink = new ScDdeLink( pDok, aAppl, aTopic, aItem, nMode );
2304             pLinkMgr->InsertDDELink( pLink, aAppl, aTopic, aItem );
2305             if ( pLinkMgr->GetLinks().Count() == 1 )                    // erster ?
2306             {
2307                 SfxBindings* pBindings = pDok->GetViewBindings();
2308                 if (pBindings)
2309                     pBindings->Invalidate( SID_LINKS );             // Link-Manager enablen
2310             }
2311 
2312                                     //! asynchron auswerten ???
2313             pLink->TryUpdate();     //  TryUpdate ruft Update nicht mehrfach auf
2314 
2315             // StartListening erst nach dem Update, sonst circular reference
2316             pMyFormulaCell->StartListening( *pLink );
2317         }
2318         else
2319         {
2320             pMyFormulaCell->StartListening( *pLink );
2321         }
2322 
2323         //  Wenn aus dem Reschedule beim Ausführen des Links ein Fehler
2324         //  (z.B. zirkuläre Referenz) entstanden ist, der vorher nicht da war,
2325         //  das Fehler-Flag zurücksetzen:
2326 
2327         if ( pMyFormulaCell->GetRawError() && !bWasError )
2328             pMyFormulaCell->SetErrCode(0);
2329 
2330             //  Wert abfragen
2331 
2332         const ScMatrix* pLinkMat = pLink->GetResult();
2333         if (pLinkMat)
2334         {
2335             SCSIZE nC, nR;
2336             pLinkMat->GetDimensions(nC, nR);
2337             ScMatrixRef pNewMat = GetNewMat( nC, nR);
2338             if (pNewMat)
2339             {
2340                 pLinkMat->MatCopy(*pNewMat);        // kopieren
2341                 PushMatrix( pNewMat );
2342             }
2343             else
2344                 PushIllegalArgument();
2345         }
2346         else
2347             PushNA();
2348 
2349         pDok->DisableIdle( bOldDis );
2350     }
2351 }
2352 
ScBase()2353 void ScInterpreter::ScBase()
2354 {   // Value, Base [, MinLen]
2355     sal_uInt8 nParamCount = GetByte();
2356     if ( MustHaveParamCount( nParamCount, 2, 3 ) )
2357     {
2358         static const sal_Unicode __FAR_DATA pDigits[] = {
2359             '0','1','2','3','4','5','6','7','8','9',
2360             'A','B','C','D','E','F','G','H','I','J','K','L','M',
2361             'N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
2362             0
2363         };
2364         static const int nDigits = (sizeof(pDigits)/sizeof(sal_Unicode))-1;
2365         xub_StrLen nMinLen;
2366         if ( nParamCount == 3 )
2367         {
2368             double fLen = ::rtl::math::approxFloor( GetDouble() );
2369             if ( 1.0 <= fLen && fLen < STRING_MAXLEN )
2370                 nMinLen = (xub_StrLen) fLen;
2371             else if ( fLen == 0.0 )
2372                 nMinLen = 1;
2373             else
2374                 nMinLen = 0;    // Error
2375         }
2376         else
2377             nMinLen = 1;
2378         double fBase = ::rtl::math::approxFloor( GetDouble() );
2379         double fVal = ::rtl::math::approxFloor( GetDouble() );
2380         double fChars = ((fVal > 0.0 && fBase > 0.0) ?
2381             (ceil( log( fVal ) / log( fBase ) ) + 2.0) :
2382             2.0);
2383         if ( fChars >= STRING_MAXLEN )
2384             nMinLen = 0;    // Error
2385 
2386         if ( !nGlobalError && nMinLen && 2 <= fBase && fBase <= nDigits && 0 <= fVal )
2387         {
2388             const xub_StrLen nConstBuf = 128;
2389             sal_Unicode aBuf[nConstBuf];
2390             xub_StrLen nBuf = Max( (xub_StrLen) fChars, (xub_StrLen) (nMinLen+1) );
2391             sal_Unicode* pBuf = (nBuf <= nConstBuf ? aBuf : new sal_Unicode[nBuf]);
2392             for ( xub_StrLen j = 0; j < nBuf; ++j )
2393             {
2394                 pBuf[j] = '0';
2395             }
2396             sal_Unicode* p = pBuf + nBuf - 1;
2397             *p = 0;
2398             if ( fVal <= (sal_uLong)(~0) )
2399             {
2400                 sal_uLong nVal = (sal_uLong) fVal;
2401                 sal_uLong nBase = (sal_uLong) fBase;
2402                 while ( nVal && p > pBuf )
2403                 {
2404                     *--p = pDigits[ nVal % nBase ];
2405                     nVal /= nBase;
2406                 }
2407                 fVal = (double) nVal;
2408             }
2409             else
2410             {
2411                 sal_Bool bDirt = sal_False;
2412                 while ( fVal && p > pBuf )
2413                 {
2414 //! mit fmod Rundungsfehler ab 2**48
2415 //                  double fDig = ::rtl::math::approxFloor( fmod( fVal, fBase ) );
2416 // so ist es etwas besser
2417                     double fInt = ::rtl::math::approxFloor( fVal / fBase );
2418                     double fMult = fInt * fBase;
2419 #if OSL_DEBUG_LEVEL > 1
2420                     // #53943# =BASIS(1e308;36) => GPF mit
2421                     // nDig = (size_t) ::rtl::math::approxFloor( fVal - fMult );
2422                     // trotz vorheriger Prüfung ob fVal >= fMult
2423                     double fDebug1 = fVal - fMult;
2424                     // fVal    := 7,5975311883090e+290
2425                     // fMult   := 7,5975311883090e+290
2426                     // fDebug1 := 1,3848924157003e+275  <- RoundOff-Error
2427                     // fVal != fMult, aber: ::rtl::math::approxEqual( fVal, fMult ) == TRUE
2428                     double fDebug2 = ::rtl::math::approxSub( fVal, fMult );
2429                     // und ::rtl::math::approxSub( fVal, fMult ) == 0
2430                     double fDebug3 = ( fInt ? fVal / fInt : 0.0 );
2431                     // Nach dem strange fDebug1 und fVal < fMult  ist eigentlich
2432                     // fDebug2 == fBase, trotzdem wird das mit einem Vergleich
2433                     // nicht erkannt, dann schlägt bDirt zu und alles wird wieder gut..
2434 
2435                     // prevent compiler warnings
2436                     (void)fDebug1; (void)fDebug2; (void)fDebug3;
2437 #endif
2438                     size_t nDig;
2439                     if ( fVal < fMult )
2440                     {   // da ist was gekippt
2441                         bDirt = sal_True;
2442                         nDig = 0;
2443                     }
2444                     else
2445                     {
2446                         double fDig = ::rtl::math::approxFloor( ::rtl::math::approxSub( fVal, fMult ) );
2447                         if ( bDirt )
2448                         {
2449                             bDirt = sal_False;
2450                             --fDig;
2451                         }
2452                         if ( fDig <= 0.0 )
2453                             nDig = 0;
2454                         else if ( fDig >= fBase )
2455                             nDig = ((size_t) fBase) - 1;
2456                         else
2457                             nDig = (size_t) fDig;
2458                     }
2459                     *--p = pDigits[ nDig ];
2460                     fVal = fInt;
2461                 }
2462             }
2463             if ( fVal )
2464                 PushError( errStringOverflow );
2465             else
2466             {
2467                 if ( nBuf - (p - pBuf) <= nMinLen )
2468                     p = pBuf + nBuf - 1 - nMinLen;
2469                 PushStringBuffer( p );
2470             }
2471             if ( pBuf != aBuf )
2472                 delete [] pBuf;
2473         }
2474         else
2475             PushIllegalArgument();
2476     }
2477 }
2478 
2479 
ScDecimal()2480 void ScInterpreter::ScDecimal()
2481 {   // Text, Base
2482     if ( MustHaveParamCount( GetByte(), 2 ) )
2483     {
2484         double fBase = ::rtl::math::approxFloor( GetDouble() );
2485         String aStr( GetString() );
2486         if ( !nGlobalError && 2 <= fBase && fBase <= 36 )
2487         {
2488             double fVal = 0.0;
2489             int nBase = (int) fBase;
2490             const sal_Unicode* p = aStr.GetBuffer();
2491             while ( *p == ' ' || *p == '\t' )
2492                 p++;        // strip leading white space
2493             if ( nBase == 16 )
2494             {   // evtl. hex-prefix strippen
2495                 if ( *p == 'x' || *p == 'X' )
2496                     p++;
2497                 else if ( *p == '0' && (*(p+1) == 'x' || *(p+1) == 'X') )
2498                     p += 2;
2499             }
2500             while ( *p )
2501             {
2502                 int n;
2503                 if ( '0' <= *p && *p <= '9' )
2504                     n = *p - '0';
2505                 else if ( 'A' <= *p && *p <= 'Z' )
2506                     n = 10 + (*p - 'A');
2507                 else if ( 'a' <= *p && *p <= 'z' )
2508                     n = 10 + (*p - 'a');
2509                 else
2510                     n = nBase;
2511                 if ( nBase <= n )
2512                 {
2513                     if ( *(p+1) == 0 &&
2514                             ( (nBase ==  2 && (*p == 'b' || *p == 'B'))
2515                             ||(nBase == 16 && (*p == 'h' || *p == 'H')) )
2516                         )
2517                         ;       // 101b und F00Dh sind ok
2518                     else
2519                     {
2520                         PushIllegalArgument();
2521                         return ;
2522                     }
2523                 }
2524                 else
2525                     fVal = fVal * fBase + n;
2526                 p++;
2527 
2528             }
2529             PushDouble( fVal );
2530         }
2531         else
2532             PushIllegalArgument();
2533     }
2534 }
2535 
2536 
ScConvert()2537 void ScInterpreter::ScConvert()
2538 {   // Value, FromUnit, ToUnit
2539     if ( MustHaveParamCount( GetByte(), 3 ) )
2540     {
2541         String aToUnit( GetString() );
2542         String aFromUnit( GetString() );
2543         double fVal = GetDouble();
2544         if ( nGlobalError )
2545             PushError( nGlobalError);
2546         else
2547         {   // erst die angegebene Reihenfolge suchen, wenn nicht gefunden den Kehrwert
2548             double fConv;
2549             if ( ScGlobal::GetUnitConverter()->GetValue( fConv, aFromUnit, aToUnit ) )
2550                 PushDouble( fVal * fConv );
2551             else if ( ScGlobal::GetUnitConverter()->GetValue( fConv, aToUnit, aFromUnit ) )
2552                 PushDouble( fVal / fConv );
2553             else
2554                 PushNA();
2555         }
2556     }
2557 }
2558 
2559 
ScRoman()2560 void ScInterpreter::ScRoman()
2561 {   // Value [Mode]
2562     sal_uInt8 nParamCount = GetByte();
2563     if( MustHaveParamCount( nParamCount, 1, 2 ) )
2564     {
2565         double fMode = (nParamCount == 2) ? ::rtl::math::approxFloor( GetDouble() ) : 0.0;
2566         double fVal = ::rtl::math::approxFloor( GetDouble() );
2567         if( nGlobalError )
2568             PushError( nGlobalError);
2569         else if( (fMode >= 0.0) && (fMode < 5.0) && (fVal >= 0.0) && (fVal < 4000.0) )
2570         {
2571             static const sal_Unicode pChars[] = { 'M', 'D', 'C', 'L', 'X', 'V', 'I' };
2572             static const sal_uInt16 pValues[] = { 1000, 500, 100, 50, 10, 5, 1 };
2573             static const sal_uInt16 nMaxIndex = (sal_uInt16)(sizeof(pValues) / sizeof(pValues[0]) - 1);
2574 
2575             String aRoman;
2576             sal_uInt16 nVal = (sal_uInt16) fVal;
2577             sal_uInt16 nMode = (sal_uInt16) fMode;
2578 
2579             for( sal_uInt16 i = 0; i <= nMaxIndex / 2; i++ )
2580             {
2581                 sal_uInt16 nIndex = 2 * i;
2582                 sal_uInt16 nDigit = nVal / pValues[ nIndex ];
2583 
2584                 if( (nDigit % 5) == 4 )
2585                 {
2586                     sal_uInt16 nIndex2 = (nDigit == 4) ? nIndex - 1 : nIndex - 2;
2587                     sal_uInt16 nSteps = 0;
2588                     while( (nSteps < nMode) && (nIndex < nMaxIndex) )
2589                     {
2590                         nSteps++;
2591                         if( pValues[ nIndex2 ] - pValues[ nIndex + 1 ] <= nVal )
2592                             nIndex++;
2593                         else
2594                             nSteps = nMode;
2595                     }
2596                     aRoman += pChars[ nIndex ];
2597                     aRoman += pChars[ nIndex2 ];
2598                     nVal = sal::static_int_cast<sal_uInt16>( nVal + pValues[ nIndex ] );
2599                     nVal = sal::static_int_cast<sal_uInt16>( nVal - pValues[ nIndex2 ] );
2600                 }
2601                 else
2602                 {
2603                     if( nDigit > 4 )
2604                         aRoman += pChars[ nIndex - 1 ];
2605                     aRoman.Expand( aRoman.Len() + (nDigit % 5), pChars[ nIndex ] );
2606                     nVal %= pValues[ nIndex ];
2607                 }
2608             }
2609 
2610             PushString( aRoman );
2611         }
2612         else
2613             PushIllegalArgument();
2614     }
2615 }
2616 
2617 
lcl_GetArabicValue(sal_Unicode cChar,sal_uInt16 & rnValue,sal_Bool & rbIsDec)2618 sal_Bool lcl_GetArabicValue( sal_Unicode cChar, sal_uInt16& rnValue, sal_Bool& rbIsDec )
2619 {
2620     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScBase" );
2621     switch( cChar )
2622     {
2623         case 'M':   rnValue = 1000; rbIsDec = sal_True;     break;
2624         case 'D':   rnValue = 500;  rbIsDec = sal_False;    break;
2625         case 'C':   rnValue = 100;  rbIsDec = sal_True;     break;
2626         case 'L':   rnValue = 50;   rbIsDec = sal_False;    break;
2627         case 'X':   rnValue = 10;   rbIsDec = sal_True;     break;
2628         case 'V':   rnValue = 5;    rbIsDec = sal_False;    break;
2629         case 'I':   rnValue = 1;    rbIsDec = sal_True;     break;
2630         default:    return sal_False;
2631     }
2632     return sal_True;
2633 }
2634 
2635 
ScArabic()2636 void ScInterpreter::ScArabic()
2637 {
2638     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScArabic" );
2639     String aRoman( GetString() );
2640     if( nGlobalError )
2641         PushError( nGlobalError);
2642     else
2643     {
2644         aRoman.ToUpperAscii();
2645 
2646         sal_uInt16 nValue = 0;
2647         sal_uInt16 nValidRest = 3999;
2648         sal_uInt16 nCharIndex = 0;
2649         sal_uInt16 nCharCount = aRoman.Len();
2650         sal_Bool bValid = sal_True;
2651 
2652         while( bValid && (nCharIndex < nCharCount) )
2653         {
2654             sal_uInt16 nDigit1 = 0;
2655             sal_uInt16 nDigit2 = 0;
2656             sal_Bool bIsDec1 = sal_False;
2657             sal_Bool bIsDec2 = sal_False;
2658             bValid = lcl_GetArabicValue( aRoman.GetChar( nCharIndex ), nDigit1, bIsDec1 );
2659             if( bValid && (nCharIndex + 1 < nCharCount) )
2660                 bValid = lcl_GetArabicValue( aRoman.GetChar( nCharIndex + 1 ), nDigit2, bIsDec2 );
2661             if( bValid )
2662             {
2663                 if( nDigit1 >= nDigit2 )
2664                 {
2665                     nValue = sal::static_int_cast<sal_uInt16>( nValue + nDigit1 );
2666                     nValidRest %= (nDigit1 * (bIsDec1 ? 5 : 2));
2667                     bValid = (nValidRest >= nDigit1);
2668                     if( bValid )
2669                         nValidRest = sal::static_int_cast<sal_uInt16>( nValidRest - nDigit1 );
2670                     nCharIndex++;
2671                 }
2672                 else if( nDigit1 * 2 != nDigit2 )
2673                 {
2674                     sal_uInt16 nDiff = nDigit2 - nDigit1;
2675                     nValue = sal::static_int_cast<sal_uInt16>( nValue + nDiff );
2676                     bValid = (nValidRest >= nDiff);
2677                     if( bValid )
2678                         nValidRest = nDigit1 - 1;
2679                     nCharIndex += 2;
2680                 }
2681                 else
2682                     bValid = sal_False;
2683             }
2684         }
2685         if( bValid )
2686             PushInt( nValue );
2687         else
2688             PushIllegalArgument();
2689     }
2690 }
2691 
2692 
ScHyperLink()2693 void ScInterpreter::ScHyperLink()
2694 {
2695     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScHyperLink" );
2696     sal_uInt8 nParamCount = GetByte();
2697     if ( MustHaveParamCount( nParamCount, 1, 2 ) )
2698     {
2699         double fVal = 0.0;
2700         String aStr;
2701         ScMatValType nResultType = SC_MATVAL_STRING;
2702 
2703         if ( nParamCount == 2 )
2704         {
2705             switch ( GetStackType() )
2706             {
2707                 case svDouble:
2708                     fVal = GetDouble();
2709                     nResultType = SC_MATVAL_VALUE;
2710                 break;
2711                 case svString:
2712                     aStr = GetString();
2713                 break;
2714                 case svSingleRef:
2715                 case svDoubleRef:
2716                 {
2717                     ScAddress aAdr;
2718                     if ( !PopDoubleRefOrSingleRef( aAdr ) )
2719                         break;
2720                     ScBaseCell* pCell = GetCell( aAdr );
2721                     if (HasCellEmptyData( pCell))
2722                         nResultType = SC_MATVAL_EMPTY;
2723                     else
2724                     {
2725                         sal_uInt16 nErr = GetCellErrCode( pCell );
2726                         if (nErr)
2727                             SetError( nErr);
2728                         else if (HasCellValueData( pCell))
2729                         {
2730                             fVal = GetCellValue( aAdr, pCell );
2731                             nResultType = SC_MATVAL_VALUE;
2732                         }
2733                         else
2734                             GetCellString( aStr, pCell );
2735                     }
2736                 }
2737                 break;
2738                 case svMatrix:
2739                     nResultType = GetDoubleOrStringFromMatrix( fVal, aStr);
2740                 break;
2741                 case svMissing:
2742                 case svEmptyCell:
2743                     Pop();
2744                     // mimic xcl
2745                     fVal = 0.0;
2746                     nResultType = SC_MATVAL_VALUE;
2747                 break;
2748                 default:
2749                     PopError();
2750                     SetError( errIllegalArgument);
2751             }
2752         }
2753         String aUrl = GetString();
2754         ScMatrixRef pResMat = GetNewMat( 1, 2);
2755         if (nGlobalError)
2756         {
2757             fVal = CreateDoubleError( nGlobalError);
2758             nResultType = SC_MATVAL_VALUE;
2759         }
2760         if (nParamCount == 2 || nGlobalError)
2761         {
2762             if (ScMatrix::IsValueType( nResultType))
2763                 pResMat->PutDouble( fVal, 0);
2764             else if (ScMatrix::IsRealStringType( nResultType))
2765                 pResMat->PutString( aStr, 0);
2766             else    // EmptyType, EmptyPathType, mimic xcl
2767                 pResMat->PutDouble( 0.0, 0 );
2768         }
2769         else
2770             pResMat->PutString( aUrl, 0 );
2771         pResMat->PutString( aUrl, 1 );
2772         bMatrixFormula = true;
2773         PushMatrix(pResMat);
2774     }
2775 }
2776 
2777 
lclConvertMoney(const String & aSearchUnit,double & rfRate,int & rnDec)2778 sal_Bool lclConvertMoney( const String& aSearchUnit, double& rfRate, int& rnDec )
2779 {
2780     struct ConvertInfo
2781     {
2782         const sal_Char* pCurrText;
2783         double          fRate;
2784         int             nDec;
2785     };
2786     ConvertInfo aConvertTable[] = {
2787         { "EUR", 1.0,      2 },
2788         { "ATS", 13.7603,  2 },
2789         { "BEF", 40.3399,  0 },
2790         { "DEM", 1.95583,  2 },
2791         { "ESP", 166.386,  0 },
2792         { "FIM", 5.94573,  2 },
2793         { "FRF", 6.55957,  2 },
2794         { "IEP", 0.787564, 2 },
2795         { "ITL", 1936.27,  0 },
2796         { "LUF", 40.3399,  0 },
2797         { "NLG", 2.20371,  2 },
2798         { "PTE", 200.482,  2 },
2799         { "GRD", 340.750,  2 },
2800         { "SIT", 239.640,  2 },
2801         { "MTL", 0.429300, 2 },
2802         { "CYP", 0.585274, 2 },
2803         { "SKK", 30.1260,  2 },
2804         { "EEK", 15.6466,  2 },
2805         { "LVL", 0.702804, 2 },
2806         { "LTL", 3.45280,  2 },
2807         { "HRK", 7.53450,  2 },
2808         { "BGN", 1.95583,  2 }
2809     };
2810 
2811     const size_t nConversionCount = sizeof( aConvertTable ) / sizeof( aConvertTable[0] );
2812     for ( size_t i = 0; i < nConversionCount; i++ )
2813         if ( aSearchUnit.EqualsIgnoreCaseAscii( aConvertTable[i].pCurrText ) )
2814         {
2815             rfRate = aConvertTable[i].fRate;
2816             rnDec  = aConvertTable[i].nDec;
2817             return sal_True;
2818         }
2819     return sal_False;
2820 }
2821 
ScEuroConvert()2822 void ScInterpreter::ScEuroConvert()
2823 {   //Value, FromUnit, ToUnit[, FullPrecision, [TriangulationPrecision]]
2824     sal_uInt8 nParamCount = GetByte();
2825     if ( MustHaveParamCount( nParamCount, 3, 5 ) )
2826     {
2827         double nPrecision = 0.0;
2828         if ( nParamCount == 5 )
2829         {
2830             nPrecision = ::rtl::math::approxFloor(GetDouble());
2831             if ( nPrecision < 3 )
2832             {
2833                 PushIllegalArgument();
2834                 return;
2835             }
2836         }
2837         sal_Bool bFullPrecision = sal_False;
2838         if ( nParamCount >= 4 )
2839             bFullPrecision = GetBool();
2840         String aToUnit( GetString() );
2841         String aFromUnit( GetString() );
2842         double fVal = GetDouble();
2843         if ( nGlobalError )
2844             PushError( nGlobalError);
2845         else
2846         {
2847             double fRes;
2848             double fFromRate;
2849             double fToRate;
2850             int    nFromDec;
2851             int    nToDec;
2852             String aEur( RTL_CONSTASCII_USTRINGPARAM("EUR"));
2853             if ( lclConvertMoney( aFromUnit, fFromRate, nFromDec )
2854                 && lclConvertMoney( aToUnit, fToRate, nToDec ) )
2855             {
2856                 if ( aFromUnit.EqualsIgnoreCaseAscii( aToUnit ) )
2857                     fRes = fVal;
2858                 else
2859                 {
2860                     if ( aFromUnit.EqualsIgnoreCaseAscii( aEur ) )
2861                        fRes = fVal * fToRate;
2862                     else
2863                     {
2864                         double fIntermediate = fVal / fFromRate;
2865                         if ( nPrecision )
2866                             fIntermediate = ::rtl::math::round( fIntermediate,
2867                                                             (int) nPrecision );
2868                         fRes = fIntermediate * fToRate;
2869                     }
2870                     if ( !bFullPrecision )
2871                         fRes = ::rtl::math::round( fRes, nToDec );
2872                 }
2873                 PushDouble( fRes );
2874             }
2875             else
2876                 PushIllegalArgument();
2877         }
2878     }
2879 }
2880 
2881 
2882 // BAHTTEXT ===================================================================
2883 
2884 #define UTF8_TH_0       "\340\270\250\340\270\271\340\270\231\340\270\242\340\271\214"
2885 #define UTF8_TH_1       "\340\270\253\340\270\231\340\270\266\340\271\210\340\270\207"
2886 #define UTF8_TH_2       "\340\270\252\340\270\255\340\270\207"
2887 #define UTF8_TH_3       "\340\270\252\340\270\262\340\270\241"
2888 #define UTF8_TH_4       "\340\270\252\340\270\265\340\271\210"
2889 #define UTF8_TH_5       "\340\270\253\340\271\211\340\270\262"
2890 #define UTF8_TH_6       "\340\270\253\340\270\201"
2891 #define UTF8_TH_7       "\340\271\200\340\270\210\340\271\207\340\270\224"
2892 #define UTF8_TH_8       "\340\271\201\340\270\233\340\270\224"
2893 #define UTF8_TH_9       "\340\271\200\340\270\201\340\271\211\340\270\262"
2894 #define UTF8_TH_10      "\340\270\252\340\270\264\340\270\232"
2895 #define UTF8_TH_11      "\340\271\200\340\270\255\340\271\207\340\270\224"
2896 #define UTF8_TH_20      "\340\270\242\340\270\265\340\271\210"
2897 #define UTF8_TH_1E2     "\340\270\243\340\271\211\340\270\255\340\270\242"
2898 #define UTF8_TH_1E3     "\340\270\236\340\270\261\340\270\231"
2899 #define UTF8_TH_1E4     "\340\270\253\340\270\241\340\270\267\340\271\210\340\270\231"
2900 #define UTF8_TH_1E5     "\340\271\201\340\270\252\340\270\231"
2901 #define UTF8_TH_1E6     "\340\270\245\340\271\211\340\270\262\340\270\231"
2902 #define UTF8_TH_DOT0    "\340\270\226\340\271\211\340\270\247\340\270\231"
2903 #define UTF8_TH_BAHT    "\340\270\232\340\270\262\340\270\227"
2904 #define UTF8_TH_SATANG  "\340\270\252\340\270\225\340\270\262\340\270\207\340\270\204\340\271\214"
2905 #define UTF8_TH_MINUS   "\340\270\245\340\270\232"
2906 
2907 #define UTF8_STRINGPARAM( ascii )   ascii, static_cast< xub_StrLen >( sizeof( ascii ) - 1 )
2908 #define UTF8_CREATE( ascii )        ByteString( UTF8_STRINGPARAM( ascii ) )
2909 #define UTF8_APPEND( ascii )        Append( UTF8_STRINGPARAM( ascii ) )
2910 #define UTF8_PREPEND( ascii )       Insert( UTF8_CREATE( ascii ), 0 )
2911 
2912 // local functions ------------------------------------------------------------
2913 
2914 namespace {
2915 
lclSplitBlock(double & rfInt,sal_Int32 & rnBlock,double fValue,double fSize)2916 inline void lclSplitBlock( double& rfInt, sal_Int32& rnBlock, double fValue, double fSize )
2917 {
2918     rnBlock = static_cast< sal_Int32 >( modf( (fValue + 0.1) / fSize, &rfInt ) * fSize + 0.1 );
2919 }
2920 
2921 /** Appends a digit (0 to 9) to the passed string. */
lclAppendDigit(ByteString & rText,sal_Int32 nDigit)2922 void lclAppendDigit( ByteString& rText, sal_Int32 nDigit )
2923 {
2924     switch( nDigit )
2925     {
2926         case 0: rText.UTF8_APPEND( UTF8_TH_0 ); break;
2927         case 1: rText.UTF8_APPEND( UTF8_TH_1 ); break;
2928         case 2: rText.UTF8_APPEND( UTF8_TH_2 ); break;
2929         case 3: rText.UTF8_APPEND( UTF8_TH_3 ); break;
2930         case 4: rText.UTF8_APPEND( UTF8_TH_4 ); break;
2931         case 5: rText.UTF8_APPEND( UTF8_TH_5 ); break;
2932         case 6: rText.UTF8_APPEND( UTF8_TH_6 ); break;
2933         case 7: rText.UTF8_APPEND( UTF8_TH_7 ); break;
2934         case 8: rText.UTF8_APPEND( UTF8_TH_8 ); break;
2935         case 9: rText.UTF8_APPEND( UTF8_TH_9 ); break;
2936         default:    DBG_ERRORFILE( "lclAppendDigit - illegal digit" );
2937     }
2938 }
2939 
2940 /** Appends a value raised to a power of 10: nDigit*10^nPow10.
2941     @param nDigit  A digit in the range from 1 to 9.
2942     @param nPow10  A value in the range from 2 to 5.
2943  */
lclAppendPow10(ByteString & rText,sal_Int32 nDigit,sal_Int32 nPow10)2944 void lclAppendPow10( ByteString& rText, sal_Int32 nDigit, sal_Int32 nPow10 )
2945 {
2946     DBG_ASSERT( (1 <= nDigit) && (nDigit <= 9), "lclAppendPow10 - illegal digit" );
2947     lclAppendDigit( rText, nDigit );
2948     switch( nPow10 )
2949     {
2950         case 2: rText.UTF8_APPEND( UTF8_TH_1E2 );   break;
2951         case 3: rText.UTF8_APPEND( UTF8_TH_1E3 );   break;
2952         case 4: rText.UTF8_APPEND( UTF8_TH_1E4 );   break;
2953         case 5: rText.UTF8_APPEND( UTF8_TH_1E5 );   break;
2954         default:    DBG_ERRORFILE( "lclAppendPow10 - illegal power" );
2955     }
2956 }
2957 
2958 /** Appends a block of 6 digits (value from 1 to 999,999) to the passed string. */
lclAppendBlock(ByteString & rText,sal_Int32 nValue)2959 void lclAppendBlock( ByteString& rText, sal_Int32 nValue )
2960 {
2961     DBG_ASSERT( (1 <= nValue) && (nValue <= 999999), "lclAppendBlock - illegal value" );
2962     if( nValue >= 100000 )
2963     {
2964         lclAppendPow10( rText, nValue / 100000, 5 );
2965         nValue %= 100000;
2966     }
2967     if( nValue >= 10000 )
2968     {
2969         lclAppendPow10( rText, nValue / 10000, 4 );
2970         nValue %= 10000;
2971     }
2972     if( nValue >= 1000 )
2973     {
2974         lclAppendPow10( rText, nValue / 1000, 3 );
2975         nValue %= 1000;
2976     }
2977     if( nValue >= 100 )
2978     {
2979         lclAppendPow10( rText, nValue / 100, 2 );
2980         nValue %= 100;
2981     }
2982     if( nValue > 0 )
2983     {
2984         sal_Int32 nTen = nValue / 10;
2985         sal_Int32 nOne = nValue % 10;
2986         if( nTen >= 1 )
2987         {
2988             if( nTen >= 3 )
2989                 lclAppendDigit( rText, nTen );
2990             else if( nTen == 2 )
2991                 rText.UTF8_APPEND( UTF8_TH_20 );
2992             rText.UTF8_APPEND( UTF8_TH_10 );
2993         }
2994         if( (nTen > 0) && (nOne == 1) )
2995             rText.UTF8_APPEND( UTF8_TH_11 );
2996         else if( nOne > 0 )
2997             lclAppendDigit( rText, nOne );
2998     }
2999 }
3000 
3001 } // namespace
3002 
3003 // ----------------------------------------------------------------------------
3004 
ScBahtText()3005 void ScInterpreter::ScBahtText()
3006 {
3007     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScBahtText" );
3008     sal_uInt8 nParamCount = GetByte();
3009     if ( MustHaveParamCount( nParamCount, 1 ) )
3010     {
3011         double fValue = GetDouble();
3012         if( nGlobalError )
3013         {
3014             PushError( nGlobalError);
3015             return;
3016         }
3017 
3018         // sign
3019         bool bMinus = fValue < 0.0;
3020         fValue = fabs( fValue );
3021 
3022         // round to 2 digits after decimal point, fValue contains Satang as integer
3023         fValue = ::rtl::math::approxFloor( fValue * 100.0 + 0.5 );
3024 
3025         // split Baht and Satang
3026         double fBaht = 0.0;
3027         sal_Int32 nSatang = 0;
3028         lclSplitBlock( fBaht, nSatang, fValue, 100.0 );
3029 
3030         ByteString aText;
3031 
3032         // generate text for Baht value
3033         if( fBaht == 0.0 )
3034         {
3035             if( nSatang == 0 )
3036                 aText.UTF8_APPEND( UTF8_TH_0 );
3037         }
3038         else while( fBaht > 0.0 )
3039         {
3040             ByteString aBlock;
3041             sal_Int32 nBlock = 0;
3042             lclSplitBlock( fBaht, nBlock, fBaht, 1.0e6 );
3043             if( nBlock > 0 )
3044                 lclAppendBlock( aBlock, nBlock );
3045             // add leading "million", if there will come more blocks
3046             if( fBaht > 0.0 )
3047                 aBlock.UTF8_PREPEND( UTF8_TH_1E6 );
3048             aText.Insert( aBlock, 0 );
3049         }
3050         if( aText.Len() > 0 )
3051             aText.UTF8_APPEND( UTF8_TH_BAHT );
3052 
3053         // generate text for Satang value
3054         if( nSatang == 0 )
3055         {
3056             aText.UTF8_APPEND( UTF8_TH_DOT0 );
3057         }
3058         else
3059         {
3060             lclAppendBlock( aText, nSatang );
3061             aText.UTF8_APPEND( UTF8_TH_SATANG );
3062         }
3063 
3064         // add the minus sign
3065         if( bMinus )
3066             aText.UTF8_PREPEND( UTF8_TH_MINUS );
3067 
3068         PushString( String( aText, RTL_TEXTENCODING_UTF8 ) );
3069     }
3070 }
3071 
3072 // ============================================================================
3073 
ScGetPivotData()3074 void ScInterpreter::ScGetPivotData()
3075 {
3076     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "sc", "er", "ScInterpreter::ScGetPivotData" );
3077     sal_uInt8 nParamCount = GetByte();
3078 
3079     if ( MustHaveParamCount( nParamCount, 2, 30 ) )
3080     {
3081         // there must be an even number of args
3082         //      target, ref, then field/item pairs
3083         if( (nParamCount % 2) == 1)
3084             goto failed;
3085 
3086         bool bOldSyntax = false;
3087         if ( nParamCount == 2 )
3088         {
3089             // if the first parameter is a ref, assume old syntax
3090             StackVar eFirstType = GetStackType( 2 );
3091             if ( eFirstType == svSingleRef || eFirstType == svDoubleRef )
3092                 bOldSyntax = true;
3093         }
3094 
3095         ScDPGetPivotDataField aTarget;                  // target field, and returns result
3096         std::vector< ScDPGetPivotDataField > aFilters;
3097         String aFilterList;
3098         if ( bOldSyntax )
3099             aFilterList = GetString();      // old syntax: second parameter is list of constraints
3100         else
3101         {
3102             // new syntax: separate name/value pairs
3103 
3104             sal_uInt16 nFilterCount = nParamCount / 2 - 1;
3105             aFilters.resize( nFilterCount );
3106 
3107             sal_uInt16 i = nFilterCount;
3108             while( i-- > 0 )
3109             {
3110                 //! should allow numeric constraint values
3111                 aFilters[i].mbValIsStr = sal_True;
3112                 aFilters[i].maValStr = GetString();
3113 
3114                 aFilters[i].maFieldName = GetString();
3115             }
3116         }
3117 
3118         // common to both syntaxes: a reference to the data pilot table
3119 
3120         ScRange aBlock;
3121         switch ( GetStackType() )
3122         {
3123             case svDoubleRef :
3124                 PopDoubleRef( aBlock );
3125                 break;
3126 
3127             case svSingleRef :
3128                 {
3129                     ScAddress aAddr;
3130                     PopSingleRef( aAddr );
3131                     aBlock = aAddr;
3132                     break;
3133                 }
3134             default:
3135                 goto failed;
3136         }
3137         // NOTE : MS Excel docs claim to use the 'most recent' which is not
3138         // exactly the same as what we do in ScDocument::GetDPAtBlock
3139         // However we do need to use GetDPABlock
3140         ScDPObject* pDPObj = pDok->GetDPAtBlock ( aBlock );
3141         if( NULL == pDPObj)
3142             goto failed;
3143 
3144         if ( bOldSyntax )
3145         {
3146             // fill aFilters / aTarget from aFilterList string
3147             if ( !pDPObj->ParseFilters( aTarget, aFilters, aFilterList ) )
3148                 goto failed;
3149         }
3150         else
3151             aTarget.maFieldName = GetString(); // new syntax: first parameter is data field name
3152 
3153         if( pDPObj->GetPivotData( aTarget, aFilters ) )
3154         {
3155             if( aTarget.mbValIsStr )
3156                 PushString( aTarget.maValStr );
3157             else
3158                 PushDouble( aTarget.mnValNum );
3159             return;
3160         }
3161     }
3162 
3163 failed :
3164     PushError( errNoRef );
3165 }
3166 
3167 /* vim: set noet sw=4 ts=4: */
3168