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 <svl/zforlist.hxx>
28
29 #include "scitems.hxx"
30 #include "attrib.hxx"
31 #include "cell.hxx"
32 #include "compiler.hxx"
33 #include "interpre.hxx"
34 #include "document.hxx"
35 #include "scmatrix.hxx"
36 #include "dociter.hxx"
37 #include "docoptio.hxx"
38 #include "rechead.hxx"
39 #include "rangenam.hxx"
40 #include "brdcst.hxx"
41 #include "ddelink.hxx"
42 #include "validat.hxx"
43 #include "progress.hxx"
44 #include "editutil.hxx"
45 #include "recursionhelper.hxx"
46 #include "postit.hxx"
47 #include "externalrefmgr.hxx"
48 #include <editeng/editobj.hxx>
49 #include <svl/intitem.hxx>
50 #include <editeng/flditem.hxx>
51 #include <svl/broadcast.hxx>
52
53 using namespace formula;
54 // More or less arbitrary, of course all recursions must fit into available
55 // stack space (which is what on all systems we don't know yet?). Choosing a
56 // lower value may be better than trying a much higher value that also isn't
57 // sufficient but temporarily leads to high memory consumption. On the other
58 // hand, if the value fits all recursions, execution is quicker as no resumes
59 // are necessary. Could be made a configurable option.
60 // Allow for a year's calendar (366).
61 const sal_uInt16 MAXRECURSION = 400;
62
63 // STATIC DATA -----------------------------------------------------------
64
65 #ifdef USE_MEMPOOL
66 // MemPools auf 4k Boundaries - 64 Bytes ausrichten
67 const sal_uInt16 nMemPoolValueCell = (0x8000 - 64) / sizeof(ScValueCell);
68 const sal_uInt16 nMemPoolFormulaCell = (0x8000 - 64) / sizeof(ScFormulaCell);
69 const sal_uInt16 nMemPoolStringCell = (0x4000 - 64) / sizeof(ScStringCell);
70 const sal_uInt16 nMemPoolNoteCell = (0x1000 - 64) / sizeof(ScNoteCell);
IMPL_FIXEDMEMPOOL_NEWDEL(ScValueCell,nMemPoolValueCell,nMemPoolValueCell)71 IMPL_FIXEDMEMPOOL_NEWDEL( ScValueCell, nMemPoolValueCell, nMemPoolValueCell )
72 IMPL_FIXEDMEMPOOL_NEWDEL( ScFormulaCell, nMemPoolFormulaCell, nMemPoolFormulaCell )
73 IMPL_FIXEDMEMPOOL_NEWDEL( ScStringCell, nMemPoolStringCell, nMemPoolStringCell )
74 IMPL_FIXEDMEMPOOL_NEWDEL( ScNoteCell, nMemPoolNoteCell, nMemPoolNoteCell )
75 #endif
76
77 // ============================================================================
78
79 ScBaseCell::ScBaseCell( CellType eNewType ) :
80 mpNote( 0 ),
81 mpBroadcaster( 0 ),
82 nTextWidth( TEXTWIDTH_DIRTY ),
83 eCellType( sal::static_int_cast<sal_uInt8>(eNewType) ),
84 nScriptType( SC_SCRIPTTYPE_UNKNOWN )
85 {
86 }
87
ScBaseCell(const ScBaseCell & rCell)88 ScBaseCell::ScBaseCell( const ScBaseCell& rCell ) :
89 mpNote( 0 ),
90 mpBroadcaster( 0 ),
91 nTextWidth( rCell.nTextWidth ),
92 eCellType( rCell.eCellType ),
93 nScriptType( SC_SCRIPTTYPE_UNKNOWN )
94 {
95 }
96
~ScBaseCell()97 ScBaseCell::~ScBaseCell()
98 {
99 delete mpNote;
100 delete mpBroadcaster;
101 DBG_ASSERT( eCellType == CELLTYPE_DESTROYED, "BaseCell Destructor" );
102 }
103
104 namespace {
105
lclCloneCell(const ScBaseCell & rSrcCell,ScDocument & rDestDoc,const ScAddress & rDestPos,int nCloneFlags)106 ScBaseCell* lclCloneCell( const ScBaseCell& rSrcCell, ScDocument& rDestDoc, const ScAddress& rDestPos, int nCloneFlags )
107 {
108 switch( rSrcCell.GetCellType() )
109 {
110 case CELLTYPE_VALUE:
111 return new ScValueCell( static_cast< const ScValueCell& >( rSrcCell ) );
112 case CELLTYPE_STRING:
113 return new ScStringCell( static_cast< const ScStringCell& >( rSrcCell ) );
114 case CELLTYPE_EDIT:
115 return new ScEditCell( static_cast< const ScEditCell& >( rSrcCell ), rDestDoc );
116 case CELLTYPE_FORMULA:
117 return new ScFormulaCell( static_cast< const ScFormulaCell& >( rSrcCell ), rDestDoc, rDestPos, nCloneFlags );
118 case CELLTYPE_NOTE:
119 return new ScNoteCell;
120 default:;
121 }
122 DBG_ERROR( "lclCloneCell - unknown cell type" );
123 return 0;
124 }
125
126 } // namespace
127
CloneWithoutNote(ScDocument & rDestDoc,int nCloneFlags) const128 ScBaseCell* ScBaseCell::CloneWithoutNote( ScDocument& rDestDoc, int nCloneFlags ) const
129 {
130 // notes will not be cloned -> cell address only needed for formula cells
131 ScAddress aDestPos;
132 if( eCellType == CELLTYPE_FORMULA )
133 aDestPos = static_cast< const ScFormulaCell* >( this )->aPos;
134 return lclCloneCell( *this, rDestDoc, aDestPos, nCloneFlags );
135 }
136
CloneWithoutNote(ScDocument & rDestDoc,const ScAddress & rDestPos,int nCloneFlags) const137 ScBaseCell* ScBaseCell::CloneWithoutNote( ScDocument& rDestDoc, const ScAddress& rDestPos, int nCloneFlags ) const
138 {
139 return lclCloneCell( *this, rDestDoc, rDestPos, nCloneFlags );
140 }
141
CloneWithNote(const ScAddress & rOwnPos,ScDocument & rDestDoc,const ScAddress & rDestPos,int nCloneFlags) const142 ScBaseCell* ScBaseCell::CloneWithNote( const ScAddress& rOwnPos, ScDocument& rDestDoc, const ScAddress& rDestPos, int nCloneFlags ) const
143 {
144 ScBaseCell* pNewCell = lclCloneCell( *this, rDestDoc, rDestPos, nCloneFlags );
145 if( mpNote )
146 {
147 if( !pNewCell )
148 pNewCell = new ScNoteCell;
149 bool bCloneCaption = (nCloneFlags & SC_CLONECELL_NOCAPTION) == 0;
150 pNewCell->TakeNote( mpNote->Clone( rOwnPos, rDestDoc, rDestPos, bCloneCaption ) );
151 }
152 return pNewCell;
153 }
154
Delete()155 void ScBaseCell::Delete()
156 {
157 DeleteNote();
158 switch (eCellType)
159 {
160 case CELLTYPE_VALUE:
161 delete (ScValueCell*) this;
162 break;
163 case CELLTYPE_STRING:
164 delete (ScStringCell*) this;
165 break;
166 case CELLTYPE_EDIT:
167 delete (ScEditCell*) this;
168 break;
169 case CELLTYPE_FORMULA:
170 delete (ScFormulaCell*) this;
171 break;
172 case CELLTYPE_NOTE:
173 delete (ScNoteCell*) this;
174 break;
175 default:
176 DBG_ERROR("Unbekannter Zellentyp");
177 break;
178 }
179 }
180
IsBlank(bool bIgnoreNotes) const181 bool ScBaseCell::IsBlank( bool bIgnoreNotes ) const
182 {
183 return (eCellType == CELLTYPE_NOTE) && (bIgnoreNotes || !mpNote);
184 }
185
TakeNote(ScPostIt * pNote)186 void ScBaseCell::TakeNote( ScPostIt* pNote )
187 {
188 delete mpNote;
189 mpNote = pNote;
190 }
191
ReleaseNote()192 ScPostIt* ScBaseCell::ReleaseNote()
193 {
194 ScPostIt* pNote = mpNote;
195 mpNote = 0;
196 return pNote;
197 }
198
DeleteNote()199 void ScBaseCell::DeleteNote()
200 {
201 DELETEZ( mpNote );
202 }
203
TakeBroadcaster(SvtBroadcaster * pBroadcaster)204 void ScBaseCell::TakeBroadcaster( SvtBroadcaster* pBroadcaster )
205 {
206 delete mpBroadcaster;
207 mpBroadcaster = pBroadcaster;
208 }
209
ReleaseBroadcaster()210 SvtBroadcaster* ScBaseCell::ReleaseBroadcaster()
211 {
212 SvtBroadcaster* pBroadcaster = mpBroadcaster;
213 mpBroadcaster = 0;
214 return pBroadcaster;
215 }
216
DeleteBroadcaster()217 void ScBaseCell::DeleteBroadcaster()
218 {
219 DELETEZ( mpBroadcaster );
220 }
221
CreateTextCell(const String & rString,ScDocument * pDoc)222 ScBaseCell* ScBaseCell::CreateTextCell( const String& rString, ScDocument* pDoc )
223 {
224 if ( rString.Search('\n') != STRING_NOTFOUND || rString.Search(CHAR_CR) != STRING_NOTFOUND )
225 return new ScEditCell( rString, pDoc );
226 else
227 return new ScStringCell( rString );
228 }
229
StartListeningTo(ScDocument * pDoc)230 void ScBaseCell::StartListeningTo( ScDocument* pDoc )
231 {
232 if ( eCellType == CELLTYPE_FORMULA && !pDoc->IsClipOrUndo()
233 && !pDoc->GetNoListening()
234 && !((ScFormulaCell*)this)->IsInChangeTrack()
235 )
236 {
237 pDoc->SetDetectiveDirty(sal_True); // es hat sich was geaendert...
238
239 ScFormulaCell* pFormCell = (ScFormulaCell*)this;
240 ScTokenArray* pArr = pFormCell->GetCode();
241 if( pArr->IsRecalcModeAlways() )
242 pDoc->StartListeningArea( BCA_LISTEN_ALWAYS, pFormCell );
243 else
244 {
245 pArr->Reset();
246 ScToken* t;
247 while ( ( t = static_cast<ScToken*>(pArr->GetNextReferenceRPN()) ) != NULL )
248 {
249 StackVar eType = t->GetType();
250 ScSingleRefData& rRef1 = t->GetSingleRef();
251 ScSingleRefData& rRef2 = (eType == svDoubleRef ?
252 t->GetDoubleRef().Ref2 : rRef1);
253 switch( eType )
254 {
255 case svSingleRef:
256 rRef1.CalcAbsIfRel( pFormCell->aPos );
257 if ( rRef1.Valid() )
258 {
259 pDoc->StartListeningCell(
260 ScAddress( rRef1.nCol,
261 rRef1.nRow,
262 rRef1.nTab ), pFormCell );
263 }
264 break;
265 case svDoubleRef:
266 t->CalcAbsIfRel( pFormCell->aPos );
267 if ( rRef1.Valid() && rRef2.Valid() )
268 {
269 if ( t->GetOpCode() == ocColRowNameAuto )
270 { // automagically
271 if ( rRef1.IsColRel() )
272 { // ColName
273 pDoc->StartListeningArea( ScRange (
274 rRef1.nCol,
275 rRef1.nRow,
276 rRef1.nTab,
277 rRef2.nCol,
278 MAXROW,
279 rRef2.nTab ), pFormCell );
280 }
281 else
282 { // RowName
283 pDoc->StartListeningArea( ScRange (
284 rRef1.nCol,
285 rRef1.nRow,
286 rRef1.nTab,
287 MAXCOL,
288 rRef2.nRow,
289 rRef2.nTab ), pFormCell );
290 }
291 }
292 else
293 {
294 pDoc->StartListeningArea( ScRange (
295 rRef1.nCol,
296 rRef1.nRow,
297 rRef1.nTab,
298 rRef2.nCol,
299 rRef2.nRow,
300 rRef2.nTab ), pFormCell );
301 }
302 }
303 break;
304 default:
305 ; // nothing
306 }
307 }
308 }
309 pFormCell->SetNeedsListening( sal_False);
310 }
311 }
312
313 // pArr gesetzt -> Referenzen von anderer Zelle nehmen
314 // dann muss auch aPos uebergeben werden!
315
EndListeningTo(ScDocument * pDoc,ScTokenArray * pArr,ScAddress aPos)316 void ScBaseCell::EndListeningTo( ScDocument* pDoc, ScTokenArray* pArr,
317 ScAddress aPos )
318 {
319 if ( eCellType == CELLTYPE_FORMULA && !pDoc->IsClipOrUndo()
320 && !((ScFormulaCell*)this)->IsInChangeTrack()
321 )
322 {
323 pDoc->SetDetectiveDirty(sal_True); // es hat sich was geaendert...
324
325 ScFormulaCell* pFormCell = (ScFormulaCell*)this;
326 if( pFormCell->GetCode()->IsRecalcModeAlways() )
327 pDoc->EndListeningArea( BCA_LISTEN_ALWAYS, pFormCell );
328 else
329 {
330 if (!pArr)
331 {
332 pArr = pFormCell->GetCode();
333 aPos = pFormCell->aPos;
334 }
335 pArr->Reset();
336 ScToken* t;
337 while ( ( t = static_cast<ScToken*>(pArr->GetNextReferenceRPN()) ) != NULL )
338 {
339 StackVar eType = t->GetType();
340 ScSingleRefData& rRef1 = t->GetSingleRef();
341 ScSingleRefData& rRef2 = (eType == svDoubleRef ?
342 t->GetDoubleRef().Ref2 : rRef1);
343 switch( eType )
344 {
345 case svSingleRef:
346 rRef1.CalcAbsIfRel( aPos );
347 if ( rRef1.Valid() )
348 {
349 pDoc->EndListeningCell(
350 ScAddress( rRef1.nCol,
351 rRef1.nRow,
352 rRef1.nTab ), pFormCell );
353 }
354 break;
355 case svDoubleRef:
356 t->CalcAbsIfRel( aPos );
357 if ( rRef1.Valid() && rRef2.Valid() )
358 {
359 if ( t->GetOpCode() == ocColRowNameAuto )
360 { // automagically
361 if ( rRef1.IsColRel() )
362 { // ColName
363 pDoc->EndListeningArea( ScRange (
364 rRef1.nCol,
365 rRef1.nRow,
366 rRef1.nTab,
367 rRef2.nCol,
368 MAXROW,
369 rRef2.nTab ), pFormCell );
370 }
371 else
372 { // RowName
373 pDoc->EndListeningArea( ScRange (
374 rRef1.nCol,
375 rRef1.nRow,
376 rRef1.nTab,
377 MAXCOL,
378 rRef2.nRow,
379 rRef2.nTab ), pFormCell );
380 }
381 }
382 else
383 {
384 pDoc->EndListeningArea( ScRange (
385 rRef1.nCol,
386 rRef1.nRow,
387 rRef1.nTab,
388 rRef2.nCol,
389 rRef2.nRow,
390 rRef2.nTab ), pFormCell );
391 }
392 }
393 break;
394 default:
395 ; // nothing
396 }
397 }
398 }
399 }
400 }
401
402
GetErrorCode() const403 sal_uInt16 ScBaseCell::GetErrorCode() const
404 {
405 switch ( eCellType )
406 {
407 case CELLTYPE_FORMULA :
408 return ((ScFormulaCell*)this)->GetErrCode();
409 default:
410 return 0;
411 }
412 }
413
414
HasEmptyData() const415 sal_Bool ScBaseCell::HasEmptyData() const
416 {
417 switch ( eCellType )
418 {
419 case CELLTYPE_NOTE :
420 return sal_True;
421 case CELLTYPE_FORMULA :
422 return ((ScFormulaCell*)this)->IsEmpty();
423 default:
424 return sal_False;
425 }
426 }
427
428
HasValueData() const429 sal_Bool ScBaseCell::HasValueData() const
430 {
431 switch ( eCellType )
432 {
433 case CELLTYPE_VALUE :
434 return sal_True;
435 case CELLTYPE_FORMULA :
436 return ((ScFormulaCell*)this)->IsValue();
437 default:
438 return sal_False;
439 }
440 }
441
442
HasStringData() const443 sal_Bool ScBaseCell::HasStringData() const
444 {
445 switch ( eCellType )
446 {
447 case CELLTYPE_STRING :
448 case CELLTYPE_EDIT :
449 return sal_True;
450 case CELLTYPE_FORMULA :
451 return !((ScFormulaCell*)this)->IsValue();
452 default:
453 return sal_False;
454 }
455 }
456
GetStringData() const457 String ScBaseCell::GetStringData() const
458 {
459 String aStr;
460 switch ( eCellType )
461 {
462 case CELLTYPE_STRING:
463 ((const ScStringCell*)this)->GetString( aStr );
464 break;
465 case CELLTYPE_EDIT:
466 ((const ScEditCell*)this)->GetString( aStr );
467 break;
468 case CELLTYPE_FORMULA:
469 ((ScFormulaCell*)this)->GetString( aStr ); // an der Formelzelle nicht-const
470 break;
471 }
472 return aStr;
473 }
474
475 // static
CellEqual(const ScBaseCell * pCell1,const ScBaseCell * pCell2)476 sal_Bool ScBaseCell::CellEqual( const ScBaseCell* pCell1, const ScBaseCell* pCell2 )
477 {
478 CellType eType1 = CELLTYPE_NONE;
479 CellType eType2 = CELLTYPE_NONE;
480 if ( pCell1 )
481 {
482 eType1 = pCell1->GetCellType();
483 if (eType1 == CELLTYPE_EDIT)
484 eType1 = CELLTYPE_STRING;
485 else if (eType1 == CELLTYPE_NOTE)
486 eType1 = CELLTYPE_NONE;
487 }
488 if ( pCell2 )
489 {
490 eType2 = pCell2->GetCellType();
491 if (eType2 == CELLTYPE_EDIT)
492 eType2 = CELLTYPE_STRING;
493 else if (eType2 == CELLTYPE_NOTE)
494 eType2 = CELLTYPE_NONE;
495 }
496 if ( eType1 != eType2 )
497 return sal_False;
498
499 switch ( eType1 ) // beide Typen gleich
500 {
501 case CELLTYPE_NONE: // beide leer
502 return sal_True;
503 case CELLTYPE_VALUE: // wirklich Value-Zellen
504 return ( ((const ScValueCell*)pCell1)->GetValue() ==
505 ((const ScValueCell*)pCell2)->GetValue() );
506 case CELLTYPE_STRING: // String oder Edit
507 {
508 String aText1;
509 if ( pCell1->GetCellType() == CELLTYPE_STRING )
510 ((const ScStringCell*)pCell1)->GetString(aText1);
511 else
512 ((const ScEditCell*)pCell1)->GetString(aText1);
513 String aText2;
514 if ( pCell2->GetCellType() == CELLTYPE_STRING )
515 ((const ScStringCell*)pCell2)->GetString(aText2);
516 else
517 ((const ScEditCell*)pCell2)->GetString(aText2);
518 return ( aText1 == aText2 );
519 }
520 case CELLTYPE_FORMULA:
521 {
522 //! eingefuegte Zeilen / Spalten beruecksichtigen !!!!!
523 //! Vergleichsfunktion an der Formelzelle ???
524 //! Abfrage mit ScColumn::SwapRow zusammenfassen!
525
526 ScTokenArray* pCode1 = ((ScFormulaCell*)pCell1)->GetCode();
527 ScTokenArray* pCode2 = ((ScFormulaCell*)pCell2)->GetCode();
528
529 if (pCode1->GetLen() == pCode2->GetLen()) // nicht-UPN
530 {
531 sal_Bool bEqual = sal_True;
532 sal_uInt16 nLen = pCode1->GetLen();
533 FormulaToken** ppToken1 = pCode1->GetArray();
534 FormulaToken** ppToken2 = pCode2->GetArray();
535 for (sal_uInt16 i=0; i<nLen; i++)
536 if ( !ppToken1[i]->TextEqual(*(ppToken2[i])) )
537 {
538 bEqual = sal_False;
539 break;
540 }
541
542 if (bEqual)
543 return sal_True;
544 }
545
546 return sal_False; // unterschiedlich lang oder unterschiedliche Tokens
547 }
548 default:
549 DBG_ERROR("huch, was fuer Zellen???");
550 }
551 return sal_False;
552 }
553
554 // ============================================================================
555
ScNoteCell(SvtBroadcaster * pBC)556 ScNoteCell::ScNoteCell( SvtBroadcaster* pBC ) :
557 ScBaseCell( CELLTYPE_NOTE )
558 {
559 TakeBroadcaster( pBC );
560 }
561
ScNoteCell(ScPostIt * pNote,SvtBroadcaster * pBC)562 ScNoteCell::ScNoteCell( ScPostIt* pNote, SvtBroadcaster* pBC ) :
563 ScBaseCell( CELLTYPE_NOTE )
564 {
565 TakeNote( pNote );
566 TakeBroadcaster( pBC );
567 }
568
569 #ifdef DBG_UTIL
~ScNoteCell()570 ScNoteCell::~ScNoteCell()
571 {
572 eCellType = CELLTYPE_DESTROYED;
573 }
574 #endif
575
576 // ============================================================================
577
ScValueCell()578 ScValueCell::ScValueCell() :
579 ScBaseCell( CELLTYPE_VALUE ),
580 mfValue( 0.0 )
581 {
582 }
583
ScValueCell(double fValue)584 ScValueCell::ScValueCell( double fValue ) :
585 ScBaseCell( CELLTYPE_VALUE ),
586 mfValue( fValue )
587 {
588 }
589
590 #ifdef DBG_UTIL
~ScValueCell()591 ScValueCell::~ScValueCell()
592 {
593 eCellType = CELLTYPE_DESTROYED;
594 }
595 #endif
596
597 // ============================================================================
598
ScStringCell()599 ScStringCell::ScStringCell() :
600 ScBaseCell( CELLTYPE_STRING )
601 {
602 }
603
ScStringCell(const String & rString)604 ScStringCell::ScStringCell( const String& rString ) :
605 ScBaseCell( CELLTYPE_STRING ),
606 maString( rString.intern() )
607 {
608 }
609
610 #ifdef DBG_UTIL
~ScStringCell()611 ScStringCell::~ScStringCell()
612 {
613 eCellType = CELLTYPE_DESTROYED;
614 }
615 #endif
616
617 // ============================================================================
618
619 //
620 // ScFormulaCell
621 //
622
ScFormulaCell()623 ScFormulaCell::ScFormulaCell() :
624 ScBaseCell( CELLTYPE_FORMULA ),
625 eTempGrammar( FormulaGrammar::GRAM_DEFAULT),
626 pCode( NULL ),
627 pDocument( NULL ),
628 pPrevious(0),
629 pNext(0),
630 pPreviousTrack(0),
631 pNextTrack(0),
632 nFormatIndex(0),
633 nFormatType( NUMBERFORMAT_NUMBER ),
634 nSeenInIteration(0),
635 cMatrixFlag ( MM_NONE ),
636 bDirty( sal_False ),
637 bChanged( sal_False ),
638 bRunning( sal_False ),
639 bCompile( sal_False ),
640 bSubTotal( sal_False ),
641 bIsIterCell( sal_False ),
642 bInChangeTrack( sal_False ),
643 bTableOpDirty( sal_False ),
644 bNeedListening( sal_False ),
645 pValidRefToken( NULL ),
646 aPos(0,0,0)
647 {
648 }
649
ScFormulaCell(ScDocument * pDoc,const ScAddress & rPos,const String & rFormula,const FormulaGrammar::Grammar eGrammar,sal_uInt8 cMatInd)650 ScFormulaCell::ScFormulaCell( ScDocument* pDoc, const ScAddress& rPos,
651 const String& rFormula,
652 const FormulaGrammar::Grammar eGrammar,
653 sal_uInt8 cMatInd ) :
654 ScBaseCell( CELLTYPE_FORMULA ),
655 eTempGrammar( eGrammar),
656 pCode( NULL ),
657 pDocument( pDoc ),
658 pPrevious(0),
659 pNext(0),
660 pPreviousTrack(0),
661 pNextTrack(0),
662 nFormatIndex(0),
663 nFormatType( NUMBERFORMAT_NUMBER ),
664 nSeenInIteration(0),
665 cMatrixFlag ( cMatInd ),
666 bDirty( sal_True ), // -> wg. Benutzung im Fkt.AutoPiloten, war: cMatInd != 0
667 bChanged( sal_False ),
668 bRunning( sal_False ),
669 bCompile( sal_False ),
670 bSubTotal( sal_False ),
671 bIsIterCell( sal_False ),
672 bInChangeTrack( sal_False ),
673 bTableOpDirty( sal_False ),
674 bNeedListening( sal_False ),
675 pValidRefToken( NULL ),
676 aPos( rPos )
677 {
678 Compile( rFormula, sal_True, eGrammar ); // bNoListening, Insert does that
679 }
680
681 // Wird von den Importfiltern verwendet
682
ScFormulaCell(ScDocument * pDoc,const ScAddress & rPos,const ScTokenArray * pArr,const FormulaGrammar::Grammar eGrammar,sal_uInt8 cInd)683 ScFormulaCell::ScFormulaCell( ScDocument* pDoc, const ScAddress& rPos,
684 const ScTokenArray* pArr,
685 const FormulaGrammar::Grammar eGrammar, sal_uInt8 cInd ) :
686 ScBaseCell( CELLTYPE_FORMULA ),
687 eTempGrammar( eGrammar),
688 pCode( pArr ? new ScTokenArray( *pArr ) : new ScTokenArray ),
689 pDocument( pDoc ),
690 pPrevious(0),
691 pNext(0),
692 pPreviousTrack(0),
693 pNextTrack(0),
694 nFormatIndex(0),
695 nFormatType( NUMBERFORMAT_NUMBER ),
696 nSeenInIteration(0),
697 cMatrixFlag ( cInd ),
698 bDirty( NULL != pArr ), // -> wg. Benutzung im Fkt.AutoPiloten, war: cInd != 0
699 bChanged( sal_False ),
700 bRunning( sal_False ),
701 bCompile( sal_False ),
702 bSubTotal( sal_False ),
703 bIsIterCell( sal_False ),
704 bInChangeTrack( sal_False ),
705 bTableOpDirty( sal_False ),
706 bNeedListening( sal_False ),
707 pValidRefToken( NULL ),
708 aPos( rPos )
709 {
710 // UPN-Array erzeugen
711 if( pCode->GetLen() && !pCode->GetCodeError() && !pCode->GetCodeLen() )
712 {
713 ScCompiler aComp( pDocument, aPos, *pCode);
714 aComp.SetGrammar(eTempGrammar);
715 bSubTotal = aComp.CompileTokenArray();
716 nFormatType = aComp.GetNumFormatType();
717 }
718 else
719 {
720 pCode->Reset();
721 if ( pCode->GetNextOpCodeRPN( ocSubTotal ) )
722 bSubTotal = sal_True;
723 }
724 }
725
ScFormulaCell(const ScFormulaCell & rCell,ScDocument & rDoc,const ScAddress & rPos,int nCloneFlags)726 ScFormulaCell::ScFormulaCell( const ScFormulaCell& rCell, ScDocument& rDoc, const ScAddress& rPos, int nCloneFlags ) :
727 ScBaseCell( rCell ),
728 SvtListener(),
729 aResult( rCell.aResult ),
730 eTempGrammar( rCell.eTempGrammar),
731 pDocument( &rDoc ),
732 pPrevious(0),
733 pNext(0),
734 pPreviousTrack(0),
735 pNextTrack(0),
736 nFormatIndex( &rDoc == rCell.pDocument ? rCell.nFormatIndex : 0 ),
737 nFormatType( rCell.nFormatType ),
738 nSeenInIteration(0),
739 cMatrixFlag ( rCell.cMatrixFlag ),
740 bDirty( rCell.bDirty ),
741 bChanged( rCell.bChanged ),
742 bRunning( sal_False ),
743 bCompile( rCell.bCompile ),
744 bSubTotal( rCell.bSubTotal ),
745 bIsIterCell( sal_False ),
746 bInChangeTrack( sal_False ),
747 bTableOpDirty( sal_False ),
748 bNeedListening( sal_False ),
749 aPos( rPos )
750 {
751 if ( rCell.pValidRefToken )
752 pValidRefToken = static_cast<ScToken*>(rCell.pValidRefToken->Clone());
753 else
754 pValidRefToken = NULL;
755
756 pCode = (rCell.pCode) ? rCell.pCode->Clone() : NULL;
757
758 if ( nCloneFlags & SC_CLONECELL_ADJUST3DREL )
759 pCode->ReadjustRelative3DReferences( rCell.aPos, aPos );
760
761 // evtl. Fehler zuruecksetzen und neu kompilieren
762 // nicht im Clipboard - da muss das Fehlerflag erhalten bleiben
763 // Spezialfall Laenge=0: als Fehlerzelle erzeugt, dann auch Fehler behalten
764 if ( pCode->GetCodeError() && !pDocument->IsClipboard() && pCode->GetLen() )
765 {
766 pCode->SetCodeError( 0 );
767 bCompile = sal_True;
768 }
769 //! Compile ColRowNames on URM_MOVE/URM_COPY _after_ UpdateReference
770 sal_Bool bCompileLater = sal_False;
771 sal_Bool bClipMode = rCell.pDocument->IsClipboard();
772 if( !bCompile )
773 { // Name references with references and ColRowNames
774 pCode->Reset();
775 ScToken* t;
776 while ( ( t = static_cast<ScToken*>(pCode->GetNextReferenceOrName()) ) != NULL && !bCompile )
777 {
778 if ( t->GetOpCode() == ocExternalRef )
779 {
780 // External name, cell, and area references.
781 bCompile = true;
782 }
783 else if ( t->GetType() == svIndex )
784 {
785 ScRangeData* pRangeData = rDoc.GetRangeName()->FindIndex( t->GetIndex() );
786 if( pRangeData )
787 {
788 if( pRangeData->HasReferences() )
789 bCompile = sal_True;
790 }
791 else
792 bCompile = sal_True; // invalid reference!
793 }
794 else if ( t->GetOpCode() == ocColRowName )
795 {
796 bCompile = sal_True; // new lookup needed
797 bCompileLater = bClipMode;
798 }
799 }
800 }
801 if( bCompile )
802 {
803 if ( !bCompileLater && bClipMode )
804 {
805 // Merging ranges needs the actual positions after UpdateReference.
806 // ColRowNames need new lookup after positions are adjusted.
807 bCompileLater = pCode->HasOpCode( ocRange) || pCode->HasOpCode( ocColRowName);
808 }
809 if ( !bCompileLater )
810 {
811 // bNoListening, not at all if in Clipboard/Undo,
812 // and not from Clipboard either, instead after Insert(Clone) and UpdateReference.
813 CompileTokenArray( sal_True );
814 }
815 }
816
817 if( nCloneFlags & SC_CLONECELL_STARTLISTENING )
818 StartListeningTo( &rDoc );
819 }
820
~ScFormulaCell()821 ScFormulaCell::~ScFormulaCell()
822 {
823 pDocument->RemoveFromFormulaTree( this );
824
825 if (pDocument->HasExternalRefManager())
826 pDocument->GetExternalRefManager()->removeRefCell(this);
827
828 delete pCode;
829 #ifdef DBG_UTIL
830 eCellType = CELLTYPE_DESTROYED;
831 #endif
832 DELETEZ(pValidRefToken);
833 }
834
GetFormula(rtl::OUStringBuffer & rBuffer,const FormulaGrammar::Grammar eGrammar) const835 void ScFormulaCell::GetFormula( rtl::OUStringBuffer& rBuffer,
836 const FormulaGrammar::Grammar eGrammar ) const
837 {
838 if( pCode->GetCodeError() && !pCode->GetLen() )
839 {
840 rBuffer = rtl::OUStringBuffer( ScGlobal::GetErrorString( pCode->GetCodeError()));
841 return;
842 }
843 else if( cMatrixFlag == MM_REFERENCE )
844 {
845 // Reference to another cell that contains a matrix formula.
846 pCode->Reset();
847 ScToken* p = static_cast<ScToken*>(pCode->GetNextReferenceRPN());
848 if( p )
849 {
850 /* FIXME: original GetFormula() code obtained
851 * pCell only if (!this->IsInChangeTrack()),
852 * GetEnglishFormula() omitted that test.
853 * Can we live without in all cases? */
854 ScBaseCell* pCell;
855 ScSingleRefData& rRef = p->GetSingleRef();
856 rRef.CalcAbsIfRel( aPos );
857 if ( rRef.Valid() )
858 pCell = pDocument->GetCell( ScAddress( rRef.nCol,
859 rRef.nRow, rRef.nTab ) );
860 else
861 pCell = NULL;
862 if (pCell && pCell->GetCellType() == CELLTYPE_FORMULA)
863 {
864 ((ScFormulaCell*)pCell)->GetFormula( rBuffer, eGrammar);
865 return;
866 }
867 else
868 {
869 ScCompiler aComp( pDocument, aPos, *pCode);
870 aComp.SetGrammar(eGrammar);
871 aComp.CreateStringFromTokenArray( rBuffer );
872 }
873 }
874 else
875 {
876 DBG_ERROR("ScFormulaCell::GetFormula: not a matrix");
877 }
878 }
879 else
880 {
881 ScCompiler aComp( pDocument, aPos, *pCode);
882 aComp.SetGrammar(eGrammar);
883 aComp.CreateStringFromTokenArray( rBuffer );
884 }
885
886 sal_Unicode ch('=');
887 rBuffer.insert( 0, &ch, 1 );
888 if( cMatrixFlag )
889 {
890 sal_Unicode ch2('{');
891 rBuffer.insert( 0, &ch2, 1);
892 rBuffer.append( sal_Unicode('}'));
893 }
894 }
895
GetFormula(String & rFormula,const FormulaGrammar::Grammar eGrammar) const896 void ScFormulaCell::GetFormula( String& rFormula, const FormulaGrammar::Grammar eGrammar ) const
897 {
898 rtl::OUStringBuffer rBuffer( rFormula );
899 GetFormula( rBuffer, eGrammar );
900 rFormula = rBuffer;
901 }
902
GetResultDimensions(SCSIZE & rCols,SCSIZE & rRows)903 void ScFormulaCell::GetResultDimensions( SCSIZE& rCols, SCSIZE& rRows )
904 {
905 if (IsDirtyOrInTableOpDirty() && pDocument->GetAutoCalc())
906 Interpret();
907
908 const ScMatrix* pMat = NULL;
909 if (!pCode->GetCodeError() && aResult.GetType() == svMatrixCell &&
910 ((pMat = static_cast<const ScToken*>(aResult.GetToken().get())->GetMatrix()) != 0))
911 pMat->GetDimensions( rCols, rRows );
912 else
913 {
914 rCols = 0;
915 rRows = 0;
916 }
917 }
918
Compile(const String & rFormula,sal_Bool bNoListening,const FormulaGrammar::Grammar eGrammar)919 void ScFormulaCell::Compile( const String& rFormula, sal_Bool bNoListening,
920 const FormulaGrammar::Grammar eGrammar )
921 {
922 //#118851#, the initialization code for pCode after it can not be gnored if it is still NULL
923 if ( pCode && pDocument->IsClipOrUndo() ) return;
924 sal_Bool bWasInFormulaTree = pDocument->IsInFormulaTree( this );
925 if ( bWasInFormulaTree )
926 pDocument->RemoveFromFormulaTree( this );
927 // pCode darf fuer Abfragen noch nicht geloescht, muss aber leer sein
928 if ( pCode )
929 pCode->Clear();
930 ScTokenArray* pCodeOld = pCode;
931 ScCompiler aComp( pDocument, aPos);
932 aComp.SetGrammar(eGrammar);
933 pCode = aComp.CompileString( rFormula );
934 if ( pCodeOld )
935 delete pCodeOld;
936 if( !pCode->GetCodeError() )
937 {
938 if ( !pCode->GetLen() && aResult.GetHybridFormula().Len() && rFormula == aResult.GetHybridFormula() )
939 { // #65994# nicht rekursiv CompileTokenArray/Compile/CompileTokenArray
940 if ( rFormula.GetChar(0) == '=' )
941 pCode->AddBad( rFormula.GetBuffer() + 1 );
942 else
943 pCode->AddBad( rFormula.GetBuffer() );
944 }
945 bCompile = sal_True;
946 CompileTokenArray( bNoListening );
947 }
948 else
949 {
950 bChanged = sal_True;
951 SetTextWidth( TEXTWIDTH_DIRTY );
952 SetScriptType( SC_SCRIPTTYPE_UNKNOWN );
953 }
954 if ( bWasInFormulaTree )
955 pDocument->PutInFormulaTree( this );
956 }
957
958
CompileTokenArray(sal_Bool bNoListening)959 void ScFormulaCell::CompileTokenArray( sal_Bool bNoListening )
960 {
961 // Not already compiled?
962 if( !pCode->GetLen() && aResult.GetHybridFormula().Len() )
963 Compile( aResult.GetHybridFormula(), bNoListening, eTempGrammar);
964 else if( bCompile && !pDocument->IsClipOrUndo() && !pCode->GetCodeError() )
965 {
966 // RPN length may get changed
967 sal_Bool bWasInFormulaTree = pDocument->IsInFormulaTree( this );
968 if ( bWasInFormulaTree )
969 pDocument->RemoveFromFormulaTree( this );
970
971 // Loading from within filter? No listening yet!
972 if( pDocument->IsInsertingFromOtherDoc() )
973 bNoListening = sal_True;
974
975 if( !bNoListening && pCode->GetCodeLen() )
976 EndListeningTo( pDocument );
977 ScCompiler aComp(pDocument, aPos, *pCode);
978 aComp.SetGrammar(pDocument->GetGrammar());
979 bSubTotal = aComp.CompileTokenArray();
980 if( !pCode->GetCodeError() )
981 {
982 nFormatType = aComp.GetNumFormatType();
983 nFormatIndex = 0;
984 bChanged = sal_True;
985 aResult.SetToken( NULL);
986 bCompile = sal_False;
987 if ( !bNoListening )
988 StartListeningTo( pDocument );
989 }
990 if ( bWasInFormulaTree )
991 pDocument->PutInFormulaTree( this );
992 }
993 }
994
995
CompileXML(ScProgress & rProgress)996 void ScFormulaCell::CompileXML( ScProgress& rProgress )
997 {
998 if ( cMatrixFlag == MM_REFERENCE )
999 { // is already token code via ScDocFunc::EnterMatrix, ScDocument::InsertMatrixFormula
1000 // just establish listeners
1001 StartListeningTo( pDocument );
1002 return ;
1003 }
1004
1005 // error cell read from office:value-type="error": no formula, recompiling would give #NAME?
1006 if ( pCode->GetCodeError() && !pCode->GetLen() )
1007 return;
1008
1009 ScCompiler aComp( pDocument, aPos, *pCode);
1010 aComp.SetGrammar(eTempGrammar);
1011 String aFormula, aFormulaNmsp;
1012 aComp.CreateStringFromXMLTokenArray( aFormula, aFormulaNmsp );
1013 pDocument->DecXMLImportedFormulaCount( aFormula.Len() );
1014 rProgress.SetStateCountDownOnPercent( pDocument->GetXMLImportedFormulaCount() );
1015 // pCode darf fuer Abfragen noch nicht geloescht, muss aber leer sein
1016 if ( pCode )
1017 pCode->Clear();
1018 ScTokenArray* pCodeOld = pCode;
1019 pCode = aComp.CompileString( aFormula, aFormulaNmsp );
1020 delete pCodeOld;
1021 if( !pCode->GetCodeError() )
1022 {
1023 if ( !pCode->GetLen() )
1024 {
1025 if ( aFormula.GetChar(0) == '=' )
1026 pCode->AddBad( aFormula.GetBuffer() + 1 );
1027 else
1028 pCode->AddBad( aFormula.GetBuffer() );
1029 }
1030 bSubTotal = aComp.CompileTokenArray();
1031 if( !pCode->GetCodeError() )
1032 {
1033 nFormatType = aComp.GetNumFormatType();
1034 nFormatIndex = 0;
1035 bChanged = sal_True;
1036 bCompile = sal_False;
1037 StartListeningTo( pDocument );
1038 }
1039 }
1040 else
1041 {
1042 bChanged = sal_True;
1043 SetTextWidth( TEXTWIDTH_DIRTY );
1044 SetScriptType( SC_SCRIPTTYPE_UNKNOWN );
1045 }
1046
1047 // Same as in Load: after loading, it must be known if ocMacro is in any formula
1048 // (for macro warning, CompileXML is called at the end of loading XML file)
1049 if ( !pDocument->GetHasMacroFunc() && pCode->HasOpCodeRPN( ocMacro ) )
1050 pDocument->SetHasMacroFunc( sal_True );
1051 }
1052
1053
CalcAfterLoad()1054 void ScFormulaCell::CalcAfterLoad()
1055 {
1056 sal_Bool bNewCompiled = sal_False;
1057 // Falls ein Calc 1.0-Doc eingelesen wird, haben wir ein Ergebnis,
1058 // aber kein TokenArray
1059 if( !pCode->GetLen() && aResult.GetHybridFormula().Len() )
1060 {
1061 Compile( aResult.GetHybridFormula(), sal_True, eTempGrammar);
1062 aResult.SetToken( NULL);
1063 bDirty = sal_True;
1064 bNewCompiled = sal_True;
1065 }
1066 // Das UPN-Array wird nicht erzeugt, wenn ein Calc 3.0-Doc eingelesen
1067 // wurde, da die RangeNames erst jetzt existieren.
1068 if( pCode->GetLen() && !pCode->GetCodeLen() && !pCode->GetCodeError() )
1069 {
1070 ScCompiler aComp(pDocument, aPos, *pCode);
1071 aComp.SetGrammar(pDocument->GetGrammar());
1072 bSubTotal = aComp.CompileTokenArray();
1073 nFormatType = aComp.GetNumFormatType();
1074 nFormatIndex = 0;
1075 bDirty = sal_True;
1076 bCompile = sal_False;
1077 bNewCompiled = sal_True;
1078 }
1079 // irgendwie koennen unter os/2 mit rotter FPU-Exception /0 ohne Err503
1080 // gespeichert werden, woraufhin spaeter im NumberFormatter die BLC Lib
1081 // bei einem fabs(-NAN) abstuerzt (#32739#)
1082 // hier fuer alle Systeme ausbuegeln, damit da auch Err503 steht
1083 if ( aResult.IsValue() && !::rtl::math::isFinite( aResult.GetDouble() ) )
1084 {
1085 DBG_ERRORFILE("Formelzelle INFINITY !!! Woher kommt das Dokument?");
1086 aResult.SetResultError( errIllegalFPOperation );
1087 bDirty = sal_True;
1088 }
1089 // DoubleRefs bei binaeren Operatoren waren vor v5.0 immer Matrix,
1090 // jetzt nur noch wenn in Matrixformel, sonst implizite Schnittmenge
1091 if ( pDocument->GetSrcVersion() < SC_MATRIX_DOUBLEREF &&
1092 GetMatrixFlag() == MM_NONE && pCode->HasMatrixDoubleRefOps() )
1093 {
1094 cMatrixFlag = MM_FORMULA;
1095 SetMatColsRows( 1, 1);
1096 }
1097 // Muss die Zelle berechnet werden?
1098 // Nach Load koennen Zellen einen Fehlercode enthalten, auch dann
1099 // Listener starten und ggbf. neu berechnen wenn nicht RECALCMODE_NORMAL
1100 if( !bNewCompiled || !pCode->GetCodeError() )
1101 {
1102 StartListeningTo( pDocument );
1103 if( !pCode->IsRecalcModeNormal() )
1104 bDirty = sal_True;
1105 }
1106 if ( pCode->IsRecalcModeAlways() )
1107 { // zufall(), heute(), jetzt() bleiben immer im FormulaTree, damit sie
1108 // auch bei jedem F9 berechnet werden.
1109 bDirty = sal_True;
1110 }
1111 // Noch kein SetDirty weil noch nicht alle Listener bekannt, erst in
1112 // SetDirtyAfterLoad.
1113 }
1114
1115
MarkUsedExternalReferences()1116 bool ScFormulaCell::MarkUsedExternalReferences()
1117 {
1118 return pCode && pDocument->MarkUsedExternalReferences( *pCode);
1119 }
1120
1121
1122 // FIXME: set to 0
1123 #define erDEBUGDOT 0
1124 // If set to 1, write output that's suitable for graphviz tools like dot.
1125 // Only node1 -> node2 entries are written, you'll have to manually surround
1126 // the file content with [strict] digraph name { ... }
1127 // The ``strict'' keyword might be necessary in case of multiple identical
1128 // paths like they occur in iterations, otherwise dot may consume too much
1129 // memory when generating the layout, or you'll get unreadable output. On the
1130 // other hand, information about recurring calculation is lost then.
1131 // Generates output only if variable nDebug is set in debugger, see below.
1132 // FIXME: currently doesn't cope with iterations and recursions. Code fragments
1133 // are a leftover from a previous debug session, meant as a pointer.
1134 #if erDEBUGDOT
1135 #include <cstdio>
1136 using ::std::fopen;
1137 using ::std::fprintf;
1138 #include <vector>
1139 static const char aDebugDotFile[] = "ttt_debug.dot";
1140 #endif
1141
Interpret()1142 void ScFormulaCell::Interpret()
1143 {
1144
1145 #if erDEBUGDOT
1146 static int nDebug = 0;
1147 static const int erDEBUGDOTRUN = 3;
1148 static FILE* pDebugFile = 0;
1149 static sal_Int32 nDebugRootCount = 0;
1150 static unsigned int nDebugPathCount = 0;
1151 static ScAddress aDebugLastPos( ScAddress::INITIALIZE_INVALID);
1152 static ScAddress aDebugThisPos( ScAddress::INITIALIZE_INVALID);
1153 typedef ::std::vector< ByteString > DebugVector;
1154 static DebugVector aDebugVec;
1155 class DebugElement
1156 {
1157 public:
1158 static void push( ScFormulaCell* pCell )
1159 {
1160 aDebugThisPos = pCell->aPos;
1161 if (aDebugVec.empty())
1162 {
1163 ByteString aR( "root_");
1164 aR += ByteString::CreateFromInt32( ++nDebugRootCount);
1165 aDebugVec.push_back( aR);
1166 }
1167 String aStr;
1168 pCell->aPos.Format( aStr, SCA_VALID | SCA_TAB_3D, pCell->GetDocument(),
1169 pCell->GetDocument()->GetAddressConvention() );
1170 ByteString aB( aStr, RTL_TEXTENCODING_UTF8);
1171 aDebugVec.push_back( aB);
1172 }
1173 static void pop()
1174 {
1175 aDebugLastPos = aDebugThisPos;
1176 if (!aDebugVec.empty())
1177 {
1178 aDebugVec.pop_back();
1179 if (aDebugVec.size() == 1)
1180 {
1181 aDebugVec.pop_back();
1182 aDebugLastPos = ScAddress( ScAddress::INITIALIZE_INVALID);
1183 }
1184 }
1185 }
1186 DebugElement( ScFormulaCell* p ) { push(p); }
1187 ~DebugElement() { pop(); }
1188 };
1189 class DebugDot
1190 {
1191 public:
1192 static void out( const char* pColor )
1193 {
1194 if (nDebug != erDEBUGDOTRUN)
1195 return;
1196 char pColorString[256];
1197 sprintf( pColorString, (*pColor ?
1198 ",color=\"%s\",fontcolor=\"%s\"" : "%s%s"), pColor,
1199 pColor);
1200 size_t n = aDebugVec.size();
1201 fprintf( pDebugFile,
1202 "\"%s\" -> \"%s\" [label=\"%u\"%s]; // v:%d\n",
1203 aDebugVec[n-2].GetBuffer(), aDebugVec[n-1].GetBuffer(),
1204 ++nDebugPathCount, pColorString, n-1);
1205 fflush( pDebugFile);
1206 }
1207 };
1208 #define erDEBUGDOT_OUT( p ) (DebugDot::out(p))
1209 #define erDEBUGDOT_ELEMENT_PUSH( p ) (DebugElement::push(p))
1210 #define erDEBUGDOT_ELEMENT_POP() (DebugElement::pop())
1211 #else
1212 #define erDEBUGDOT_OUT( p )
1213 #define erDEBUGDOT_ELEMENT_PUSH( p )
1214 #define erDEBUGDOT_ELEMENT_POP()
1215 #endif
1216
1217 if (!IsDirtyOrInTableOpDirty() || pDocument->GetRecursionHelper().IsInReturn())
1218 return; // no double/triple processing
1219
1220 //! HACK:
1221 // Wenn der Aufruf aus einem Reschedule im DdeLink-Update kommt, dirty stehenlassen
1222 // Besser: Dde-Link Update ohne Reschedule oder ganz asynchron !!!
1223
1224 if ( pDocument->IsInDdeLinkUpdate() )
1225 return;
1226
1227 #if erDEBUGDOT
1228 // set nDebug=1 in debugger to init things
1229 if (nDebug == 1)
1230 {
1231 ++nDebug;
1232 pDebugFile = fopen( aDebugDotFile, "a");
1233 if (!pDebugFile)
1234 nDebug = 0;
1235 else
1236 nDebug = erDEBUGDOTRUN;
1237 }
1238 // set nDebug=3 (erDEBUGDOTRUN) in debugger to get any output
1239 DebugElement aDebugElem( this);
1240 // set nDebug=5 in debugger to close output
1241 if (nDebug == 5)
1242 {
1243 nDebug = 0;
1244 fclose( pDebugFile);
1245 pDebugFile = 0;
1246 }
1247 #endif
1248
1249 if (bRunning)
1250 {
1251
1252 #if erDEBUGDOT
1253 if (!pDocument->GetRecursionHelper().IsDoingIteration() ||
1254 aDebugThisPos != aDebugLastPos)
1255 erDEBUGDOT_OUT(aDebugThisPos == aDebugLastPos ? "orange" :
1256 (pDocument->GetRecursionHelper().GetIteration() ? "blue" :
1257 "red"));
1258 #endif
1259
1260 if (!pDocument->GetDocOptions().IsIter())
1261 {
1262 aResult.SetResultError( errCircularReference );
1263 return;
1264 }
1265
1266 if (aResult.GetResultError() == errCircularReference)
1267 aResult.SetResultError( 0 );
1268
1269 // Start or add to iteration list.
1270 if (!pDocument->GetRecursionHelper().IsDoingIteration() ||
1271 !pDocument->GetRecursionHelper().GetRecursionInIterationStack().top()->bIsIterCell)
1272 pDocument->GetRecursionHelper().SetInIterationReturn( true);
1273
1274 return;
1275 }
1276 // #63038# no multiple interprets for GetErrCode, IsValue, GetValue and
1277 // different entry point recursions. Would also lead to premature
1278 // convergence in iterations.
1279 if (pDocument->GetRecursionHelper().GetIteration() && nSeenInIteration ==
1280 pDocument->GetRecursionHelper().GetIteration())
1281 return ;
1282
1283 erDEBUGDOT_OUT( pDocument->GetRecursionHelper().GetIteration() ? "magenta" : "");
1284
1285 ScRecursionHelper& rRecursionHelper = pDocument->GetRecursionHelper();
1286 sal_Bool bOldRunning = bRunning;
1287 if (rRecursionHelper.GetRecursionCount() > MAXRECURSION)
1288 {
1289 bRunning = sal_True;
1290 rRecursionHelper.SetInRecursionReturn( true);
1291 }
1292 else
1293 {
1294 InterpretTail( SCITP_NORMAL);
1295 }
1296
1297 // While leaving a recursion or iteration stack, insert its cells to the
1298 // recursion list in reverse order.
1299 if (rRecursionHelper.IsInReturn())
1300 {
1301 if (rRecursionHelper.GetRecursionCount() > 0 ||
1302 !rRecursionHelper.IsDoingRecursion())
1303 rRecursionHelper.Insert( this, bOldRunning, aResult);
1304 bool bIterationFromRecursion = false;
1305 bool bResumeIteration = false;
1306 do
1307 {
1308 if ((rRecursionHelper.IsInIterationReturn() &&
1309 rRecursionHelper.GetRecursionCount() == 0 &&
1310 !rRecursionHelper.IsDoingIteration()) ||
1311 bIterationFromRecursion || bResumeIteration)
1312 {
1313 ScFormulaCell* pIterCell = this; // scope for debug convenience
1314 bool & rDone = rRecursionHelper.GetConvergingReference();
1315 rDone = false;
1316 if (!bIterationFromRecursion && bResumeIteration)
1317 {
1318 bResumeIteration = false;
1319 // Resuming iteration expands the range.
1320 ScFormulaRecursionList::const_iterator aOldStart(
1321 rRecursionHelper.GetLastIterationStart());
1322 rRecursionHelper.ResumeIteration();
1323 // Mark new cells being in iteration.
1324 for (ScFormulaRecursionList::const_iterator aIter(
1325 rRecursionHelper.GetIterationStart()); aIter !=
1326 aOldStart; ++aIter)
1327 {
1328 pIterCell = (*aIter).pCell;
1329 pIterCell->bIsIterCell = sal_True;
1330 }
1331 // Mark older cells dirty again, in case they converted
1332 // without accounting for all remaining cells in the circle
1333 // that weren't touched so far, e.g. conditional. Restore
1334 // backuped result.
1335 sal_uInt16 nIteration = rRecursionHelper.GetIteration();
1336 for (ScFormulaRecursionList::const_iterator aIter(
1337 aOldStart); aIter !=
1338 rRecursionHelper.GetIterationEnd(); ++aIter)
1339 {
1340 pIterCell = (*aIter).pCell;
1341 if (pIterCell->nSeenInIteration == nIteration)
1342 {
1343 if (!pIterCell->bDirty || aIter == aOldStart)
1344 {
1345 pIterCell->aResult = (*aIter).aPreviousResult;
1346 }
1347 --pIterCell->nSeenInIteration;
1348 }
1349 pIterCell->bDirty = sal_True;
1350 }
1351 }
1352 else
1353 {
1354 bResumeIteration = false;
1355 // Close circle once.
1356 rRecursionHelper.GetList().back().pCell->InterpretTail(
1357 SCITP_CLOSE_ITERATION_CIRCLE);
1358 // Start at 1, init things.
1359 rRecursionHelper.StartIteration();
1360 // Mark all cells being in iteration.
1361 for (ScFormulaRecursionList::const_iterator aIter(
1362 rRecursionHelper.GetIterationStart()); aIter !=
1363 rRecursionHelper.GetIterationEnd(); ++aIter)
1364 {
1365 pIterCell = (*aIter).pCell;
1366 pIterCell->bIsIterCell = sal_True;
1367 }
1368 }
1369 bIterationFromRecursion = false;
1370 sal_uInt16 nIterMax = pDocument->GetDocOptions().GetIterCount();
1371 for ( ; rRecursionHelper.GetIteration() <= nIterMax && !rDone;
1372 rRecursionHelper.IncIteration())
1373 {
1374 rDone = true;
1375 for ( ScFormulaRecursionList::iterator aIter(
1376 rRecursionHelper.GetIterationStart()); aIter !=
1377 rRecursionHelper.GetIterationEnd() &&
1378 !rRecursionHelper.IsInReturn(); ++aIter)
1379 {
1380 pIterCell = (*aIter).pCell;
1381 if (pIterCell->IsDirtyOrInTableOpDirty() &&
1382 rRecursionHelper.GetIteration() !=
1383 pIterCell->GetSeenInIteration())
1384 {
1385 (*aIter).aPreviousResult = pIterCell->aResult;
1386 pIterCell->InterpretTail( SCITP_FROM_ITERATION);
1387 }
1388 rDone = rDone && !pIterCell->IsDirtyOrInTableOpDirty();
1389 }
1390 if (rRecursionHelper.IsInReturn())
1391 {
1392 bResumeIteration = true;
1393 break; // for
1394 // Don't increment iteration.
1395 }
1396 }
1397 if (!bResumeIteration)
1398 {
1399 if (rDone)
1400 {
1401 for (ScFormulaRecursionList::const_iterator aIter(
1402 rRecursionHelper.GetIterationStart());
1403 aIter != rRecursionHelper.GetIterationEnd();
1404 ++aIter)
1405 {
1406 pIterCell = (*aIter).pCell;
1407 pIterCell->bIsIterCell = sal_False;
1408 pIterCell->nSeenInIteration = 0;
1409 pIterCell->bRunning = (*aIter).bOldRunning;
1410 }
1411 }
1412 else
1413 {
1414 for (ScFormulaRecursionList::const_iterator aIter(
1415 rRecursionHelper.GetIterationStart());
1416 aIter != rRecursionHelper.GetIterationEnd();
1417 ++aIter)
1418 {
1419 pIterCell = (*aIter).pCell;
1420 pIterCell->bIsIterCell = sal_False;
1421 pIterCell->nSeenInIteration = 0;
1422 pIterCell->bRunning = (*aIter).bOldRunning;
1423 // If one cell didn't converge, all cells of this
1424 // circular dependency don't, no matter whether
1425 // single cells did.
1426 pIterCell->bDirty = sal_False;
1427 pIterCell->bTableOpDirty = sal_False;
1428 pIterCell->aResult.SetResultError( errNoConvergence);
1429 pIterCell->bChanged = sal_True;
1430 pIterCell->SetTextWidth( TEXTWIDTH_DIRTY);
1431 pIterCell->SetScriptType( SC_SCRIPTTYPE_UNKNOWN);
1432 }
1433 }
1434 // End this iteration and remove entries.
1435 rRecursionHelper.EndIteration();
1436 bResumeIteration = rRecursionHelper.IsDoingIteration();
1437 }
1438 }
1439 if (rRecursionHelper.IsInRecursionReturn() &&
1440 rRecursionHelper.GetRecursionCount() == 0 &&
1441 !rRecursionHelper.IsDoingRecursion())
1442 {
1443 bIterationFromRecursion = false;
1444 // Iterate over cells known so far, start with the last cell
1445 // encountered, inserting new cells if another recursion limit
1446 // is reached. Repeat until solved.
1447 rRecursionHelper.SetDoingRecursion( true);
1448 do
1449 {
1450 rRecursionHelper.SetInRecursionReturn( false);
1451 for (ScFormulaRecursionList::const_iterator aIter(
1452 rRecursionHelper.GetStart());
1453 !rRecursionHelper.IsInReturn() && aIter !=
1454 rRecursionHelper.GetEnd(); ++aIter)
1455 {
1456 ScFormulaCell* pCell = (*aIter).pCell;
1457 if (pCell->IsDirtyOrInTableOpDirty())
1458 {
1459 pCell->InterpretTail( SCITP_NORMAL);
1460 if (!pCell->IsDirtyOrInTableOpDirty() && !pCell->IsIterCell())
1461 pCell->bRunning = (*aIter).bOldRunning;
1462 }
1463 }
1464 } while (rRecursionHelper.IsInRecursionReturn());
1465 rRecursionHelper.SetDoingRecursion( false);
1466 if (rRecursionHelper.IsInIterationReturn())
1467 {
1468 if (!bResumeIteration)
1469 bIterationFromRecursion = true;
1470 }
1471 else if (bResumeIteration ||
1472 rRecursionHelper.IsDoingIteration())
1473 rRecursionHelper.GetList().erase(
1474 rRecursionHelper.GetStart(),
1475 rRecursionHelper.GetLastIterationStart());
1476 else
1477 rRecursionHelper.Clear();
1478 }
1479 } while (bIterationFromRecursion || bResumeIteration);
1480 }
1481 }
1482
InterpretTail(ScInterpretTailParameter eTailParam)1483 void ScFormulaCell::InterpretTail( ScInterpretTailParameter eTailParam )
1484 {
1485 class RecursionCounter
1486 {
1487 ScRecursionHelper& rRec;
1488 bool bStackedInIteration;
1489 public:
1490 RecursionCounter( ScRecursionHelper& r, ScFormulaCell* p ) : rRec(r)
1491 {
1492 bStackedInIteration = rRec.IsDoingIteration();
1493 if (bStackedInIteration)
1494 rRec.GetRecursionInIterationStack().push( p);
1495 rRec.IncRecursionCount();
1496 }
1497 ~RecursionCounter()
1498 {
1499 rRec.DecRecursionCount();
1500 if (bStackedInIteration)
1501 rRec.GetRecursionInIterationStack().pop();
1502 }
1503 } aRecursionCounter( pDocument->GetRecursionHelper(), this);
1504 nSeenInIteration = pDocument->GetRecursionHelper().GetIteration();
1505 if( !pCode->GetCodeLen() && !pCode->GetCodeError() )
1506 {
1507 // #i11719# no UPN and no error and no token code but result string present
1508 // => interpretation of this cell during name-compilation and unknown names
1509 // => can't exchange underlying code array in CompileTokenArray() /
1510 // Compile() because interpreter's token iterator would crash.
1511 // This should only be a temporary condition and, since we set an
1512 // error, if ran into it again we'd bump into the dirty-clearing
1513 // condition further down.
1514 if ( !pCode->GetLen() && aResult.GetHybridFormula().Len() )
1515 {
1516 pCode->SetCodeError( errNoCode );
1517 // This is worth an assertion; if encountered in daily work
1518 // documents we might need another solution. Or just confirm correctness.
1519 DBG_ERRORFILE( "ScFormulaCell::Interpret: no UPN, no error, no token, but string" );
1520 return;
1521 }
1522 CompileTokenArray();
1523 }
1524
1525 if( pCode->GetCodeLen() && pDocument )
1526 {
1527 class StackCleaner
1528 {
1529 ScDocument* pDoc;
1530 ScInterpreter* pInt;
1531 public:
1532 StackCleaner( ScDocument* pD, ScInterpreter* pI )
1533 : pDoc(pD), pInt(pI)
1534 {}
1535 ~StackCleaner()
1536 {
1537 delete pInt;
1538 pDoc->DecInterpretLevel();
1539 }
1540 };
1541 pDocument->IncInterpretLevel();
1542 ScInterpreter* p = new ScInterpreter( this, pDocument, aPos, *pCode );
1543 StackCleaner aStackCleaner( pDocument, p);
1544 sal_uInt16 nOldErrCode = aResult.GetResultError();
1545 if ( nSeenInIteration == 0 )
1546 { // Only the first time
1547 // With bChanged=sal_False, if a newly compiled cell has a result of
1548 // 0.0, no change is detected and the cell will not be repainted.
1549 // bChanged = sal_False;
1550 aResult.SetResultError( 0 );
1551 }
1552
1553 switch ( aResult.GetResultError() )
1554 {
1555 case errCircularReference : // will be determined again if so
1556 aResult.SetResultError( 0 );
1557 break;
1558 }
1559
1560 sal_Bool bOldRunning = bRunning;
1561 bRunning = sal_True;
1562 p->Interpret();
1563 if (pDocument->GetRecursionHelper().IsInReturn() && eTailParam != SCITP_CLOSE_ITERATION_CIRCLE)
1564 {
1565 if (nSeenInIteration > 0)
1566 --nSeenInIteration; // retry when iteration is resumed
1567 return;
1568 }
1569 bRunning = bOldRunning;
1570 //-> i120962: If the cell was applied reference formula, get the valid token
1571 if (pValidRefToken)
1572 DELETEZ(pValidRefToken);
1573 if (p->IsReferenceFunc() && p->GetLastStackRefToken())
1574 pValidRefToken = static_cast<ScToken*>(p->GetLastStackRefToken()->Clone());
1575 //<- i120962
1576
1577 // #i102616# For single-sheet saving consider only content changes, not format type,
1578 // because format type isn't set on loading (might be changed later)
1579 sal_Bool bContentChanged = sal_False;
1580
1581 // Do not create a HyperLink() cell if the formula results in an error.
1582 if( p->GetError() && pCode->IsHyperLink())
1583 pCode->SetHyperLink(sal_False);
1584
1585 if( p->GetError() && p->GetError() != errCircularReference)
1586 {
1587 bDirty = sal_False;
1588 bTableOpDirty = sal_False;
1589 bChanged = sal_True;
1590 }
1591 if (eTailParam == SCITP_FROM_ITERATION && IsDirtyOrInTableOpDirty())
1592 {
1593 bool bIsValue = aResult.IsValue(); // the previous type
1594 // Did it converge?
1595 if ((bIsValue && p->GetResultType() == svDouble && fabs(
1596 p->GetNumResult() - aResult.GetDouble()) <=
1597 pDocument->GetDocOptions().GetIterEps()) ||
1598 (!bIsValue && p->GetResultType() == svString &&
1599 p->GetStringResult() == aResult.GetString()))
1600 {
1601 // A convergence in the first iteration doesn't necessarily
1602 // mean that it's done, it may be because not all related cells
1603 // of a circle changed their values yet. If the set really
1604 // converges it will do so also during the next iteration. This
1605 // fixes situations like of #i44115#. If this wasn't wanted an
1606 // initial "uncalculated" value would be needed for all cells
1607 // of a circular dependency => graph needed before calculation.
1608 if (nSeenInIteration > 1 ||
1609 pDocument->GetDocOptions().GetIterCount() == 1)
1610 {
1611 bDirty = sal_False;
1612 bTableOpDirty = sal_False;
1613 }
1614 }
1615 }
1616
1617 // New error code?
1618 if( p->GetError() != nOldErrCode )
1619 {
1620 bChanged = sal_True;
1621 // bContentChanged only has to be set if the file content would be changed
1622 if ( aResult.GetCellResultType() != svUnknown )
1623 bContentChanged = sal_True;
1624 }
1625 // Different number format?
1626 if( nFormatType != p->GetRetFormatType() )
1627 {
1628 nFormatType = p->GetRetFormatType();
1629 bChanged = sal_True;
1630 }
1631 if( nFormatIndex != p->GetRetFormatIndex() )
1632 {
1633 nFormatIndex = p->GetRetFormatIndex();
1634 bChanged = sal_True;
1635 }
1636
1637 // In case of changes just obtain the result, no temporary and
1638 // comparison needed anymore.
1639 if (bChanged)
1640 {
1641 // #i102616# Compare anyway if the sheet is still marked unchanged for single-sheet saving
1642 // Also handle special cases of initial results after loading.
1643
1644 if ( !bContentChanged && pDocument->IsStreamValid(aPos.Tab()) )
1645 {
1646 ScFormulaResult aNewResult( p->GetResultToken());
1647 StackVar eOld = aResult.GetCellResultType();
1648 StackVar eNew = aNewResult.GetCellResultType();
1649 if ( eOld == svUnknown && ( eNew == svError || ( eNew == svDouble && aNewResult.GetDouble() == 0.0 ) ) )
1650 {
1651 // ScXMLTableRowCellContext::EndElement doesn't call SetFormulaResultDouble for 0
1652 // -> no change
1653 }
1654 else
1655 {
1656 if ( eOld == svHybridCell ) // string result from SetFormulaResultString?
1657 eOld = svString; // ScHybridCellToken has a valid GetString method
1658
1659 // #i106045# use approxEqual to compare with stored value
1660 bContentChanged = (eOld != eNew ||
1661 (eNew == svDouble && !rtl::math::approxEqual( aResult.GetDouble(), aNewResult.GetDouble() )) ||
1662 (eNew == svString && aResult.GetString() != aNewResult.GetString()));
1663 }
1664 }
1665
1666 aResult.SetToken( p->GetResultToken() );
1667 }
1668 else
1669 {
1670 ScFormulaResult aNewResult( p->GetResultToken());
1671 StackVar eOld = aResult.GetCellResultType();
1672 StackVar eNew = aNewResult.GetCellResultType();
1673 bChanged = (eOld != eNew ||
1674 (eNew == svDouble && aResult.GetDouble() != aNewResult.GetDouble()) ||
1675 (eNew == svString && aResult.GetString() != aNewResult.GetString()));
1676
1677 // #i102616# handle special cases of initial results after loading (only if the sheet is still marked unchanged)
1678 if ( bChanged && !bContentChanged && pDocument->IsStreamValid(aPos.Tab()) )
1679 {
1680 if ( ( eOld == svUnknown && ( eNew == svError || ( eNew == svDouble && aNewResult.GetDouble() == 0.0 ) ) ) ||
1681 ( eOld == svHybridCell && eNew == svString && aResult.GetString() == aNewResult.GetString() ) ||
1682 ( eOld == svDouble && eNew == svDouble && rtl::math::approxEqual( aResult.GetDouble(), aNewResult.GetDouble() ) ) )
1683 {
1684 // no change, see above
1685 }
1686 else
1687 bContentChanged = sal_True;
1688 }
1689
1690 aResult.Assign( aNewResult);
1691 }
1692
1693 // Precision as shown?
1694 if ( aResult.IsValue() && !p->GetError()
1695 && pDocument->GetDocOptions().IsCalcAsShown()
1696 && nFormatType != NUMBERFORMAT_DATE
1697 && nFormatType != NUMBERFORMAT_TIME
1698 && nFormatType != NUMBERFORMAT_DATETIME )
1699 {
1700 sal_uLong nFormat = pDocument->GetNumberFormat( aPos );
1701 if ( nFormatIndex && (nFormat % SV_COUNTRY_LANGUAGE_OFFSET) == 0 )
1702 nFormat = nFormatIndex;
1703 if ( (nFormat % SV_COUNTRY_LANGUAGE_OFFSET) == 0 )
1704 nFormat = ScGlobal::GetStandardFormat(
1705 *pDocument->GetFormatTable(), nFormat, nFormatType );
1706 aResult.SetDouble( pDocument->RoundValueAsShown(
1707 aResult.GetDouble(), nFormat));
1708 }
1709 if (eTailParam == SCITP_NORMAL)
1710 {
1711 bDirty = sal_False;
1712 bTableOpDirty = sal_False;
1713 }
1714 if( aResult.GetMatrix().Is() )
1715 {
1716 // If the formula wasn't entered as a matrix formula, live on with
1717 // the upper left corner and let reference counting delete the matrix.
1718 if( cMatrixFlag != MM_FORMULA && !pCode->IsHyperLink() )
1719 aResult.SetToken( aResult.GetCellResultToken());
1720 }
1721 if ( aResult.IsValue() && !::rtl::math::isFinite( aResult.GetDouble() ) )
1722 {
1723 // Coded double error may occur via filter import.
1724 sal_uInt16 nErr = GetDoubleErrorValue( aResult.GetDouble());
1725 aResult.SetResultError( nErr);
1726 bChanged = bContentChanged = true;
1727 }
1728 if( bChanged )
1729 {
1730 SetTextWidth( TEXTWIDTH_DIRTY );
1731 SetScriptType( SC_SCRIPTTYPE_UNKNOWN );
1732 }
1733 if (bContentChanged && pDocument->IsStreamValid(aPos.Tab()))
1734 {
1735 // pass bIgnoreLock=sal_True, because even if called from pending row height update,
1736 // a changed result must still reset the stream flag
1737 pDocument->SetStreamValid(aPos.Tab(), sal_False, sal_True);
1738 }
1739 if ( !pCode->IsRecalcModeAlways() )
1740 pDocument->RemoveFromFormulaTree( this );
1741
1742 // FORCED Zellen auch sofort auf Gueltigkeit testen (evtl. Makro starten)
1743
1744 if ( pCode->IsRecalcModeForced() )
1745 {
1746 sal_uLong nValidation = ((const SfxUInt32Item*) pDocument->GetAttr(
1747 aPos.Col(), aPos.Row(), aPos.Tab(), ATTR_VALIDDATA ))->GetValue();
1748 if ( nValidation )
1749 {
1750 const ScValidationData* pData = pDocument->GetValidationEntry( nValidation );
1751 if ( pData && !pData->IsDataValid( this, aPos ) )
1752 pData->DoCalcError( this );
1753 }
1754 }
1755
1756 // Reschedule verlangsamt das ganze erheblich, nur bei Prozentaenderung ausfuehren
1757 ScProgress::GetInterpretProgress()->SetStateCountDownOnPercent(
1758 pDocument->GetFormulaCodeInTree()/MIN_NO_CODES_PER_PROGRESS_UPDATE );
1759 }
1760 else
1761 {
1762 // Zelle bei Compiler-Fehlern nicht ewig auf dirty stehenlassen
1763 DBG_ASSERT( pCode->GetCodeError(), "kein UPN-Code und kein Fehler ?!?!" );
1764 bDirty = sal_False;
1765 bTableOpDirty = sal_False;
1766 }
1767 }
1768
1769
SetMatColsRows(SCCOL nCols,SCROW nRows)1770 void ScFormulaCell::SetMatColsRows( SCCOL nCols, SCROW nRows )
1771 {
1772 ScMatrixFormulaCellToken* pMat = aResult.GetMatrixFormulaCellTokenNonConst();
1773 if (pMat)
1774 pMat->SetMatColsRows( nCols, nRows);
1775 else if (nCols || nRows)
1776 aResult.SetToken( new ScMatrixFormulaCellToken( nCols, nRows));
1777 }
1778
1779
GetMatColsRows(SCCOL & nCols,SCROW & nRows) const1780 void ScFormulaCell::GetMatColsRows( SCCOL & nCols, SCROW & nRows ) const
1781 {
1782 const ScMatrixFormulaCellToken* pMat = aResult.GetMatrixFormulaCellToken();
1783 if (pMat)
1784 pMat->GetMatColsRows( nCols, nRows);
1785 else
1786 {
1787 nCols = 0;
1788 nRows = 0;
1789 }
1790 }
1791
1792
GetStandardFormat(SvNumberFormatter & rFormatter,sal_uLong nFormat) const1793 sal_uLong ScFormulaCell::GetStandardFormat( SvNumberFormatter& rFormatter, sal_uLong nFormat ) const
1794 {
1795 if ( nFormatIndex && (nFormat % SV_COUNTRY_LANGUAGE_OFFSET) == 0 )
1796 return nFormatIndex;
1797 //! not ScFormulaCell::IsValue(), that could reinterpret the formula again.
1798 if ( aResult.IsValue() )
1799 return ScGlobal::GetStandardFormat( aResult.GetDouble(), rFormatter, nFormat, nFormatType );
1800 else
1801 return ScGlobal::GetStandardFormat( rFormatter, nFormat, nFormatType );
1802 }
1803
1804
Notify(SvtBroadcaster &,const SfxHint & rHint)1805 void __EXPORT ScFormulaCell::Notify( SvtBroadcaster&, const SfxHint& rHint)
1806 {
1807 if ( !pDocument->IsInDtorClear() && !pDocument->GetHardRecalcState() )
1808 {
1809 const ScHint* p = PTR_CAST( ScHint, &rHint );
1810 sal_uLong nHint = (p ? p->GetId() : 0);
1811 if (nHint & (SC_HINT_DATACHANGED | SC_HINT_DYING | SC_HINT_TABLEOPDIRTY))
1812 {
1813 sal_Bool bForceTrack = sal_False;
1814 if ( nHint & SC_HINT_TABLEOPDIRTY )
1815 {
1816 bForceTrack = !bTableOpDirty;
1817 if ( !bTableOpDirty )
1818 {
1819 pDocument->AddTableOpFormulaCell( this );
1820 bTableOpDirty = sal_True;
1821 }
1822 }
1823 else
1824 {
1825 bForceTrack = !bDirty;
1826 bDirty = sal_True;
1827 }
1828 // #35962# Don't remove from FormulaTree to put in FormulaTrack to
1829 // put in FormulaTree again and again, only if necessary.
1830 // Any other means except RECALCMODE_ALWAYS by which a cell could
1831 // be in FormulaTree if it would notify other cells through
1832 // FormulaTrack which weren't in FormulaTrack/FormulaTree before?!?
1833 // #87866# Yes. The new TableOpDirty made it necessary to have a
1834 // forced mode where formulas may still be in FormulaTree from
1835 // TableOpDirty but have to notify dependents for normal dirty.
1836 if ( (bForceTrack || !pDocument->IsInFormulaTree( this )
1837 || pCode->IsRecalcModeAlways())
1838 && !pDocument->IsInFormulaTrack( this ) )
1839 pDocument->AppendToFormulaTrack( this );
1840 }
1841 }
1842 }
1843
SetDirty()1844 void ScFormulaCell::SetDirty()
1845 {
1846 if ( !IsInChangeTrack() )
1847 {
1848 if ( pDocument->GetHardRecalcState() )
1849 bDirty = sal_True;
1850 else
1851 {
1852 // Mehrfach-FormulaTracking in Load und in CompileAll
1853 // nach CopyScenario und CopyBlockFromClip vermeiden.
1854 // Wenn unbedingtes FormulaTracking noetig, vor SetDirty bDirty=sal_False
1855 // setzen, z.B. in CompileTokenArray
1856 if ( !bDirty || !pDocument->IsInFormulaTree( this ) )
1857 {
1858 bDirty = sal_True;
1859 pDocument->AppendToFormulaTrack( this );
1860 pDocument->TrackFormulas();
1861 }
1862 }
1863
1864 if (pDocument->IsStreamValid(aPos.Tab()))
1865 pDocument->SetStreamValid(aPos.Tab(), sal_False);
1866 }
1867 }
1868
SetDirtyAfterLoad()1869 void ScFormulaCell::SetDirtyAfterLoad()
1870 {
1871 bDirty = sal_True;
1872 if ( !pDocument->GetHardRecalcState() )
1873 pDocument->PutInFormulaTree( this );
1874 }
1875
SetTableOpDirty()1876 void ScFormulaCell::SetTableOpDirty()
1877 {
1878 if ( !IsInChangeTrack() )
1879 {
1880 if ( pDocument->GetHardRecalcState() )
1881 bTableOpDirty = sal_True;
1882 else
1883 {
1884 if ( !bTableOpDirty || !pDocument->IsInFormulaTree( this ) )
1885 {
1886 if ( !bTableOpDirty )
1887 {
1888 pDocument->AddTableOpFormulaCell( this );
1889 bTableOpDirty = sal_True;
1890 }
1891 pDocument->AppendToFormulaTrack( this );
1892 pDocument->TrackFormulas( SC_HINT_TABLEOPDIRTY );
1893 }
1894 }
1895 }
1896 }
1897
1898
IsDirtyOrInTableOpDirty() const1899 sal_Bool ScFormulaCell::IsDirtyOrInTableOpDirty() const
1900 {
1901 return bDirty || (bTableOpDirty && pDocument->IsInInterpreterTableOp());
1902 }
1903
1904
SetErrCode(sal_uInt16 n)1905 void ScFormulaCell::SetErrCode( sal_uInt16 n )
1906 {
1907 /* FIXME: check the numerous places where ScTokenArray::GetCodeError() is
1908 * used whether it is solely for transport of a simple result error and get
1909 * rid of that abuse. */
1910 pCode->SetCodeError( n );
1911 // Hard set errors are transported as result type value per convention,
1912 // e.g. via clipboard. ScFormulaResult::IsValue() and
1913 // ScFormulaResult::GetDouble() handle that.
1914 aResult.SetResultError( n );
1915 }
1916
AddRecalcMode(ScRecalcMode nBits)1917 void ScFormulaCell::AddRecalcMode( ScRecalcMode nBits )
1918 {
1919 if ( (nBits & RECALCMODE_EMASK) != RECALCMODE_NORMAL )
1920 bDirty = sal_True;
1921 if ( nBits & RECALCMODE_ONLOAD_ONCE )
1922 { // OnLoadOnce nur zum Dirty setzen nach Filter-Import
1923 nBits = (nBits & ~RECALCMODE_EMASK) | RECALCMODE_NORMAL;
1924 }
1925 pCode->AddRecalcMode( nBits );
1926 }
1927
1928 // Dynamically create the URLField on a mouse-over action on a hyperlink() cell.
GetURLResult(String & rURL,String & rCellText)1929 void ScFormulaCell::GetURLResult( String& rURL, String& rCellText )
1930 {
1931 String aCellString;
1932
1933 Color* pColor;
1934
1935 // Cell Text uses the Cell format while the URL uses
1936 // the default format for the type.
1937 sal_uLong nCellFormat = pDocument->GetNumberFormat( aPos );
1938 SvNumberFormatter* pFormatter = pDocument->GetFormatTable();
1939
1940 if ( (nCellFormat % SV_COUNTRY_LANGUAGE_OFFSET) == 0 )
1941 nCellFormat = GetStandardFormat( *pFormatter,nCellFormat );
1942
1943 sal_uLong nURLFormat = ScGlobal::GetStandardFormat( *pFormatter,nCellFormat, NUMBERFORMAT_NUMBER);
1944
1945 if ( IsValue() )
1946 {
1947 double fValue = GetValue();
1948 pFormatter->GetOutputString( fValue, nCellFormat, rCellText, &pColor );
1949 }
1950 else
1951 {
1952 GetString( aCellString );
1953 pFormatter->GetOutputString( aCellString, nCellFormat, rCellText, &pColor );
1954 }
1955 ScConstMatrixRef xMat( aResult.GetMatrix());
1956 if (xMat)
1957 {
1958 ScMatValType nMatValType;
1959 // determine if the matrix result is a string or value.
1960 const ScMatrixValue* pMatVal = xMat->Get(0, 1, nMatValType);
1961 if (pMatVal)
1962 {
1963 if (!ScMatrix::IsValueType( nMatValType))
1964 rURL = pMatVal->GetString();
1965 else
1966 pFormatter->GetOutputString( pMatVal->fVal, nURLFormat, rURL, &pColor );
1967 }
1968 }
1969
1970 if(!rURL.Len())
1971 {
1972 if(IsValue())
1973 pFormatter->GetOutputString( GetValue(), nURLFormat, rURL, &pColor );
1974 else
1975 pFormatter->GetOutputString( aCellString, nURLFormat, rURL, &pColor );
1976 }
1977 }
1978
IsMultilineResult()1979 bool ScFormulaCell::IsMultilineResult()
1980 {
1981 if (!IsValue())
1982 return aResult.IsMultiline();
1983 return false;
1984 }
1985
CreateURLObject()1986 EditTextObject* ScFormulaCell::CreateURLObject()
1987 {
1988 String aCellText;
1989 String aURL;
1990 GetURLResult( aURL, aCellText );
1991
1992 SvxURLField aUrlField( aURL, aCellText, SVXURLFORMAT_APPDEFAULT);
1993 EditEngine& rEE = pDocument->GetEditEngine();
1994 rEE.SetText( EMPTY_STRING );
1995 rEE.QuickInsertField( SvxFieldItem( aUrlField, EE_FEATURE_FIELD ), ESelection( EE_PARA_MAX, EE_INDEX_MAX ) );
1996
1997 return rEE.CreateTextObject();
1998 }
1999
2000 // ============================================================================
2001
ScDetectiveRefIter(ScFormulaCell * pCell)2002 ScDetectiveRefIter::ScDetectiveRefIter( ScFormulaCell* pCell )
2003 {
2004 pCode = pCell->GetCode();
2005 pCode->Reset();
2006 aPos = pCell->aPos;
2007 }
2008
lcl_ScDetectiveRefIter_SkipRef(ScToken * p)2009 sal_Bool lcl_ScDetectiveRefIter_SkipRef( ScToken* p )
2010 {
2011 ScSingleRefData& rRef1 = p->GetSingleRef();
2012 if ( rRef1.IsColDeleted() || rRef1.IsRowDeleted() || rRef1.IsTabDeleted()
2013 || !rRef1.Valid() )
2014 return sal_True;
2015 if ( p->GetType() == svDoubleRef )
2016 {
2017 ScSingleRefData& rRef2 = p->GetDoubleRef().Ref2;
2018 if ( rRef2.IsColDeleted() || rRef2.IsRowDeleted() || rRef2.IsTabDeleted()
2019 || !rRef2.Valid() )
2020 return sal_True;
2021 }
2022 return sal_False;
2023 }
2024
GetNextRef(ScRange & rRange)2025 sal_Bool ScDetectiveRefIter::GetNextRef( ScRange& rRange )
2026 {
2027 sal_Bool bRet = sal_False;
2028
2029 ScToken* p = static_cast<ScToken*>(pCode->GetNextReferenceRPN());
2030 if (p)
2031 p->CalcAbsIfRel( aPos );
2032
2033 while ( p && lcl_ScDetectiveRefIter_SkipRef( p ) )
2034 {
2035 p = static_cast<ScToken*>(pCode->GetNextReferenceRPN());
2036 if (p)
2037 p->CalcAbsIfRel( aPos );
2038 }
2039
2040 if( p )
2041 {
2042 SingleDoubleRefProvider aProv( *p );
2043 rRange.aStart.Set( aProv.Ref1.nCol, aProv.Ref1.nRow, aProv.Ref1.nTab );
2044 rRange.aEnd.Set( aProv.Ref2.nCol, aProv.Ref2.nRow, aProv.Ref2.nTab );
2045 bRet = sal_True;
2046 }
2047
2048 return bRet;
2049 }
2050
2051 // ============================================================================
2052