xref: /trunk/main/sc/inc/cell.hxx (revision 38d50f7b)
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 
23 
24 #ifndef SC_CELL_HXX
25 #define SC_CELL_HXX
26 
27 #include <stddef.h>
28 
29 #include <set>
30 #include <tools/mempool.hxx>
31 #include <svl/listener.hxx>
32 #include "global.hxx"
33 #include "rangenam.hxx"
34 #include "formula/grammar.hxx"
35 #include "tokenarray.hxx"
36 #include "formularesult.hxx"
37 #include <rtl/ustrbuf.hxx>
38 #include <unotools/fontcvt.hxx>
39 #include "scdllapi.h"
40 
41 #define USE_MEMPOOL
42 #define TEXTWIDTH_DIRTY		0xffff
43 
44 // in addition to SCRIPTTYPE_... flags from scripttypeitem.hxx:
45 // set (in nScriptType) if type has not been determined yet
46 #define SC_SCRIPTTYPE_UNKNOWN	0x08
47 
48 class ScDocument;
49 class EditTextObject;
50 class ScMatrix;
51 class SvtBroadcaster;
52 class ScCodeArray;
53 class ScProgress;
54 class ScPostIt;
55 
56 // ============================================================================
57 
58 /** Default cell clone flags: do not start listening, do not adjust 3D refs to
59     old position, clone note captions of cell notes. */
60 const int SC_CLONECELL_DEFAULT          = 0x0000;
61 
62 /** If set, cloned formula cells will start to listen to the document. */
63 const int SC_CLONECELL_STARTLISTENING   = 0x0001;
64 
65 /** If set, relative 3D references of cloned formula cells will be adjusted to
66     old position (used while swapping cells for sorting a cell range). */
67 const int SC_CLONECELL_ADJUST3DREL      = 0x0002;
68 
69 /** If set, the caption object of a cell note will not be cloned (used while
70     copying cells to undo document, where captions are handled in drawing undo). */
71 const int SC_CLONECELL_NOCAPTION        = 0x0004;
72 
73 // ============================================================================
74 
75 class SC_DLLPUBLIC ScBaseCell
76 {
77 protected:
78 					~ScBaseCell();	// nicht virtuell -> darf nicht direkt aufgerufen werden
79 
80 public:
81     explicit        ScBaseCell( CellType eNewType );
82 
83     /** Base copy constructor. Does NOT clone cell note or broadcaster! */
84                     ScBaseCell( const ScBaseCell& rCell );
85 
86     /** Returns a clone of this cell at the same position, cell note and
87         broadcaster will not be cloned. */
88     ScBaseCell*     CloneWithoutNote( ScDocument& rDestDoc, int nCloneFlags = SC_CLONECELL_DEFAULT ) const;
89 
90     /** Returns a clone of this cell for the passed document position, cell
91         note and broadcaster will not be cloned. */
92     ScBaseCell*     CloneWithoutNote( ScDocument& rDestDoc, const ScAddress& rDestPos, int nCloneFlags = SC_CLONECELL_DEFAULT ) const;
93 
94     /** Returns a clone of this cell, clones cell note and caption object too
95         (unless SC_CLONECELL_NOCAPTION flag is set). Broadcaster will not be cloned. */
96     ScBaseCell*     CloneWithNote( const ScAddress& rOwnPos, ScDocument& rDestDoc, const ScAddress& rDestPos, int nCloneFlags = SC_CLONECELL_DEFAULT ) const;
97 
98     /** Due to the fact that ScBaseCell does not have a vtable, this function
99         deletes the cell by calling the appropriate d'tor of the derived class. */
100     void            Delete();
101 
102     inline CellType GetCellType() const	{ return (CellType)eCellType; }
103 
104     /** Returns true, if the cell is empty (neither value nor formula nor cell note).
105         Returns false for formula cells returning nothing, use HasEmptyData() for that. */
106     bool            IsBlank( bool bIgnoreNotes = false ) const;
107 
108 // fuer Idle-Berechnung
109     inline sal_uInt16   GetTextWidth() const { return nTextWidth; }
110     inline void     SetTextWidth( sal_uInt16 nNew ) { nTextWidth = nNew; }
111 
112     inline sal_uInt8     GetScriptType() const { return nScriptType; }
113     inline void     SetScriptType( sal_uInt8 nNew ) { nScriptType = nNew; }
114 
115     /** Returns true, if the cell contains a note. */
116     inline bool     HasNote() const { return mpNote != 0; }
117     /** Returns the pointer to a cell note object (read-only). */
118     inline const ScPostIt* GetNote() const { return mpNote; }
119     /** Returns the pointer to a cell note object. */
120     inline ScPostIt* GetNote() { return mpNote; }
121     /** Takes ownership of the passed cell note object. */
122     void            TakeNote( ScPostIt* pNote );
123     /** Returns and forgets the own cell note object. Caller takes ownership! */
124     ScPostIt*       ReleaseNote();
125     /** Deletes the own cell note object. */
126     void            DeleteNote();
127 
128     /** Returns true, if the cell contains a broadcaster. */
129     inline bool     HasBroadcaster() const { return mpBroadcaster != 0; }
130     /** Returns the pointer to the cell broadcaster. */
131     inline SvtBroadcaster* GetBroadcaster() const { return mpBroadcaster; }
132     /** Takes ownership of the passed cell broadcaster. */
133     void            TakeBroadcaster( SvtBroadcaster* pBroadcaster );
134     /** Returns and forgets the own cell broadcaster. Caller takes ownership! */
135     SvtBroadcaster* ReleaseBroadcaster();
136     /** Deletes the own cell broadcaster. */
137     void            DeleteBroadcaster();
138 
139 						// String- oder EditCell
140 	static ScBaseCell* CreateTextCell( const String& rString, ScDocument* );
141 
142     // nOnlyNames may be one or more of SC_LISTENING_NAMES_*
143 	void			StartListeningTo( ScDocument* pDoc );
144 	void			EndListeningTo( ScDocument* pDoc,
145 									ScTokenArray* pArr = NULL,
146 									ScAddress aPos = ScAddress() );
147 
148     /** Error code if ScFormulaCell, else 0. */
149     sal_uInt16          GetErrorCode() const;
150     /** ScFormulaCell with formula::svEmptyCell result, or ScNoteCell (may have been
151         created due to reference to empty cell). */
152 	sal_Bool			HasEmptyData() const;
153 	sal_Bool			HasValueData() const;
154 	sal_Bool			HasStringData() const;
155 	String			GetStringData() const;			// nur echte Strings
156 
157 	static sal_Bool		CellEqual( const ScBaseCell* pCell1, const ScBaseCell* pCell2 );
158 
159 private:
160     ScBaseCell&     operator=( const ScBaseCell& );
161 
162 private:
163     ScPostIt*       mpNote;         /// The cell note. Cell takes ownership!
164     SvtBroadcaster* mpBroadcaster;  /// Broadcaster for changed values. Cell takes ownership!
165 
166 protected:
167     sal_uInt16          nTextWidth;
168     sal_uInt8            eCellType;      // enum CellType - sal_uInt8 spart Speicher
169     sal_uInt8            nScriptType;
170 };
171 
172 // ============================================================================
173 
174 class SC_DLLPUBLIC ScNoteCell : public ScBaseCell
175 {
176 public:
177 #ifdef USE_MEMPOOL
178 	DECL_FIXEDMEMPOOL_NEWDEL( ScNoteCell )
179 #endif
180 
181     /** Cell takes ownership of the passed broadcaster. */
182     explicit        ScNoteCell( SvtBroadcaster* pBC = 0 );
183     /** Cell takes ownership of the passed note and broadcaster. */
184     explicit        ScNoteCell( ScPostIt* pNote, SvtBroadcaster* pBC = 0 );
185 
186 #ifdef DBG_UTIL
187 					~ScNoteCell();
188 #endif
189 
190 private:
191                     ScNoteCell( const ScNoteCell& );
192 };
193 
194 // ============================================================================
195 
196 class SC_DLLPUBLIC ScValueCell : public ScBaseCell
197 {
198 public:
199 #ifdef USE_MEMPOOL
200 	DECL_FIXEDMEMPOOL_NEWDEL( ScValueCell )
201 #endif
202 					ScValueCell();
203     explicit		ScValueCell( double fValue );
204 
205 #ifdef DBG_UTIL
206 					~ScValueCell();
207 #endif
208 
209     inline void     SetValue( double fValue ) { mfValue = fValue; }
210     inline double   GetValue() const { return mfValue; }
211 
212 private:
213 	double		    mfValue;
214 };
215 
216 // ============================================================================
217 
218 class SC_DLLPUBLIC ScStringCell : public ScBaseCell
219 {
220 public:
221 #ifdef USE_MEMPOOL
222 	DECL_FIXEDMEMPOOL_NEWDEL( ScStringCell )
223 #endif
224 
225 					ScStringCell();
226     explicit		ScStringCell( const String& rString );
227 
228 #ifdef DBG_UTIL
229 					~ScStringCell();
230 #endif
231 
232     inline void		SetString( const String& rString ) { maString = rString; }
233     inline void		GetString( String& rString ) const { rString = maString; }
234 	inline const String& GetString() const { return maString; }
235 
236 private:
237 	String		    maString;
238 };
239 
240 // ============================================================================
241 
242 class SC_DLLPUBLIC ScEditCell : public ScBaseCell
243 {
244 private:
245 	EditTextObject*		pData;
246 	String*				pString;		// fuer schnelleren Zugriff von Formeln
247 	ScDocument*			pDoc;			// fuer EditEngine Zugriff mit Pool
248 
249 	void			SetTextObject( const EditTextObject* pObject,
250 									const SfxItemPool* pFromPool );
251 
252 					// not implemented
253 					ScEditCell( const ScEditCell& );
254 
255 public:
256 
257 #ifdef USE_MEMPOOL
258 	DECL_FIXEDMEMPOOL_NEWDEL( ScEditCell )
259 #endif
260 
261 					~ScEditCell();				// wegen pData immer!
262 
263 					ScEditCell( const EditTextObject* pObject, ScDocument*,
264 								const SfxItemPool* pFromPool /* = NULL */ );
265                     ScEditCell( const ScEditCell& rCell, ScDocument& rDoc );
266 					// fuer Zeilenumbrueche
267 					ScEditCell( const String& rString, ScDocument* );
268 
269 	void			SetData( const EditTextObject* pObject,
270 							const SfxItemPool* pFromPool /* = NULL */ );
271 	void			GetData( const EditTextObject*& rpObject ) const;
272 	void			GetString( String& rString ) const;
273 
274 	const EditTextObject* GetData() const	{ return pData; }
275 };
276 
277 // ============================================================================
278 
279 enum ScMatrixMode {
280     MM_NONE      = 0,                   // No matrix formula
281     MM_FORMULA   = 1,                   // Upper left matrix formula cell
282     MM_REFERENCE = 2,                   // Remaining cells, via ocMatRef reference token
283     MM_FAKE      = 3                    // Interpret "as-if" matrix formula (legacy)
284 };
285 
286 class SC_DLLPUBLIC ScFormulaCell : public ScBaseCell, public SvtListener
287 {
288 private:
289     ScFormulaResult aResult;
290     formula::FormulaGrammar::Grammar  eTempGrammar;   // used between string (creation) and (re)compilation
291     ScTokenArray*   pCode;              // The (new) token array
292     ScDocument*     pDocument;
293     ScFormulaCell*  pPrevious;
294     ScFormulaCell*  pNext;
295     ScFormulaCell*  pPreviousTrack;
296     ScFormulaCell*  pNextTrack;
297     sal_uLong           nFormatIndex;       // Number format set by calculation
298     short           nFormatType;        // Number format type set by calculation
299     sal_uInt16          nSeenInIteration;   // Iteration cycle in which the cell was last encountered
300     sal_uInt8            cMatrixFlag;        // One of ScMatrixMode
301     sal_Bool            bDirty         : 1; // Must be (re)calculated
302     sal_Bool            bChanged       : 1; // Whether something changed regarding display/representation
303     sal_Bool            bRunning       : 1; // Already interpreting right now
304     sal_Bool            bCompile       : 1; // Must be (re)compiled
305     sal_Bool            bSubTotal      : 1; // Cell is part of or contains a SubTotal
306     sal_Bool            bIsIterCell    : 1; // Cell is part of a circular reference
307     sal_Bool            bInChangeTrack : 1; // Cell is in ChangeTrack
308     sal_Bool            bTableOpDirty  : 1; // Dirty flag for TableOp
309     sal_Bool            bNeedListening : 1; // Listeners need to be re-established after UpdateReference
310 
311                     enum ScInterpretTailParameter
312                     {
313                         SCITP_NORMAL,
314                         SCITP_FROM_ITERATION,
315                         SCITP_CLOSE_ITERATION_CIRCLE
316                     };
317 	void			InterpretTail( ScInterpretTailParameter );
318 
319     ScFormulaCell( const ScFormulaCell& );
320 
321 public:
322 
323 #ifdef USE_MEMPOOL
324 	DECL_FIXEDMEMPOOL_NEWDEL( ScFormulaCell )
325 #endif
326 
327 	ScAddress		aPos;
328 
329 					~ScFormulaCell();
330 					ScFormulaCell();
331 
332     /** Empty formula cell, or with a preconstructed token array. */
333     ScFormulaCell( ScDocument*, const ScAddress&, const ScTokenArray* = NULL,
334                     const formula::FormulaGrammar::Grammar = formula::FormulaGrammar::GRAM_DEFAULT,
335                     sal_uInt8 = MM_NONE );
336 
337     /** With formula string and grammar to compile with.
338        formula::FormulaGrammar::GRAM_DEFAULT effectively isformula::FormulaGrammar::GRAM_NATIVE_UI that
339         also includes formula::FormulaGrammar::CONV_UNSPECIFIED, therefor uses the address
340         convention associated with rPos::nTab by default. */
341     ScFormulaCell( ScDocument* pDoc, const ScAddress& rPos,
342                     const String& rFormula,
343                     const formula::FormulaGrammar::Grammar = formula::FormulaGrammar::GRAM_DEFAULT,
344                     sal_uInt8 cMatInd = MM_NONE );
345 
346     ScFormulaCell( const ScFormulaCell& rCell, ScDocument& rDoc, const ScAddress& rPos, int nCloneFlags = SC_CLONECELL_DEFAULT );
347 
348 	void			GetFormula( String& rFormula,
349 								const formula::FormulaGrammar::Grammar = formula::FormulaGrammar::GRAM_DEFAULT ) const;
350 	void			GetFormula( rtl::OUStringBuffer& rBuffer,
351 								const formula::FormulaGrammar::Grammar = formula::FormulaGrammar::GRAM_DEFAULT ) const;
352 
353 	void			SetDirty();
354 	inline void		SetDirtyVar() { bDirty = sal_True; }
355     // If setting entire document dirty after load, no broadcasts but still append to FormulaTree.
356     void            SetDirtyAfterLoad();
357 	inline void		ResetTableOpDirtyVar() { bTableOpDirty = sal_False; }
358 	void			SetTableOpDirty();
359 	sal_Bool			IsDirtyOrInTableOpDirty() const;
360 	sal_Bool			GetDirty() const { return bDirty; }
361     sal_Bool            NeedsListening() const { return bNeedListening; }
362     void            SetNeedsListening( sal_Bool bVar ) { bNeedListening = bVar; }
363 	void			Compile(const String& rFormula,
364 							sal_Bool bNoListening = sal_False,
365                             const formula::FormulaGrammar::Grammar = formula::FormulaGrammar::GRAM_DEFAULT );
366 	void			CompileTokenArray( sal_Bool bNoListening = sal_False );
367 	void			CompileXML( ScProgress& rProgress );		// compile temporary string tokens
368 	void			CalcAfterLoad();
369     bool            MarkUsedExternalReferences();
370 	void			Interpret();
371     inline sal_Bool     IsIterCell() const { return bIsIterCell; }
372     inline sal_uInt16   GetSeenInIteration() const { return nSeenInIteration; }
373 
374 	sal_Bool			HasOneReference( ScRange& r ) const;
375     /* Checks if the formula contains reference list that can be
376        expressed by one reference (like A1;A2;A3:A5 -> A1:A5). The
377        reference list is not required to be sorted (i.e. A3;A1;A2 is
378        still recognized as A1:A3), but no overlapping is allowed.
379        If one reference is recognized, the rRange is filled.
380 
381        It is similar to HasOneReference(), but more general.
382      */
383     bool HasRefListExpressibleAsOneReference(ScRange& rRange) const;
384 	sal_Bool			HasRelNameReference() const;
385 	sal_Bool			HasColRowName() const;
386 
387 	void			UpdateReference(UpdateRefMode eUpdateRefMode,
388 									const ScRange& r,
389 									SCsCOL nDx, SCsROW nDy, SCsTAB nDz,
390                                     ScDocument* pUndoDoc = NULL,
391                                     const ScAddress* pUndoCellPos = NULL );
392 
393 	void			TransposeReference();
394 	void			UpdateTranspose( const ScRange& rSource, const ScAddress& rDest,
395 										ScDocument* pUndoDoc );
396 
397 	void			UpdateGrow( const ScRange& rArea, SCCOL nGrowX, SCROW nGrowY );
398 
399 	void			UpdateInsertTab(SCTAB nTable);
400 	void 			UpdateInsertTabAbs(SCTAB nTable);
401 	sal_Bool			UpdateDeleteTab(SCTAB nTable, sal_Bool bIsMove = sal_False);
402 	void			UpdateMoveTab(SCTAB nOldPos, SCTAB nNewPos, SCTAB nTabNo);
403 	void			UpdateRenameTab(SCTAB nTable, const String& rName);
404 	sal_Bool 			TestTabRefAbs(SCTAB nTable);
405 	void			UpdateCompile( sal_Bool bForceIfNameInUse = sal_False );
406 	sal_Bool			IsRangeNameInUse(sal_uInt16 nIndex) const;
407     void            FindRangeNamesInUse(std::set<sal_uInt16>& rIndexes) const;
408 	void 			ReplaceRangeNamesInUse( const ScRangeData::IndexMap& rMap );
409 	sal_Bool			IsSubTotal() const 						{ return bSubTotal; }
410 	sal_Bool			IsChanged() const  						{ return bChanged; }
411 	void			ResetChanged()							{ bChanged = sal_False; }
412 	sal_Bool			IsEmpty();      // formula::svEmptyCell result
413                     // display as empty string if formula::svEmptyCell result
414 	sal_Bool			IsEmptyDisplayedAsString();
415 	sal_Bool			IsValue();      // also sal_True if formula::svEmptyCell
416 	double			GetValue();
417 	double			GetValueAlways();	// ignore errors
418 	void			GetString( String& rString );
419 	const ScMatrix* GetMatrix();
420 	sal_Bool			GetMatrixOrigin( ScAddress& rPos ) const;
421 	void			GetResultDimensions( SCSIZE& rCols, SCSIZE& rRows );
422 	sal_uInt16 			GetMatrixEdge( ScAddress& rOrgPos );
423 	sal_uInt16			GetErrCode();   // interpret first if necessary
424 	sal_uInt16			GetRawError();  // don't interpret, just return code or result error
425 	short			GetFormatType() const   				{ return nFormatType; }
426 	sal_uLong			GetFormatIndex() const					{ return nFormatIndex; }
427 	void			GetFormatInfo( short& nType, sal_uLong& nIndex ) const
428 						{ nType = nFormatType; nIndex = nFormatIndex; }
429 	sal_uInt8			GetMatrixFlag() const   				{ return cMatrixFlag; }
430 	ScTokenArray*   GetCode() const                         { return pCode; }
431 
432 	sal_Bool			IsRunning() const						{ return bRunning; }
433 	void			SetRunning( sal_Bool bVal )					{ bRunning = bVal; }
434 	void 			CompileDBFormula();
435 	void 			CompileDBFormula( sal_Bool bCreateFormulaString );
436 	void 			CompileNameFormula( sal_Bool bCreateFormulaString );
437 	void 			CompileColRowNameFormula();
438 	ScFormulaCell*	GetPrevious() const					{ return pPrevious; }
439 	ScFormulaCell*	GetNext() const						{ return pNext; }
440 	void			SetPrevious( ScFormulaCell* pF )	{ pPrevious = pF; }
441 	void			SetNext( ScFormulaCell* pF )		{ pNext = pF; }
442 	ScFormulaCell*	GetPreviousTrack() const				{ return pPreviousTrack; }
443 	ScFormulaCell*	GetNextTrack() const					{ return pNextTrack; }
444 	void			SetPreviousTrack( ScFormulaCell* pF )	{ pPreviousTrack = pF; }
445 	void			SetNextTrack( ScFormulaCell* pF )		{ pNextTrack = pF; }
446 
447 	virtual void    Notify( SvtBroadcaster& rBC, const SfxHint& rHint);
448 	void			SetCompile( sal_Bool bVal ) { bCompile = bVal; }
449 	ScDocument*		GetDocument() const		{ return pDocument; }
450 	void			SetMatColsRows( SCCOL nCols, SCROW nRows );
451 	void			GetMatColsRows( SCCOL& nCols, SCROW& nRows ) const;
452 
453 					// ob Zelle im ChangeTrack und nicht im echten Dokument ist
454 	void			SetInChangeTrack( sal_Bool bVal ) { bInChangeTrack = bVal; }
455 	sal_Bool			IsInChangeTrack() const { return bInChangeTrack; }
456 
457 					// Zu Typ und Format das entsprechende Standardformat.
458 					// Bei Format "Standard" evtl. das in die Formelzelle
459 					// uebernommene Format.
460 	sal_uLong			GetStandardFormat( SvNumberFormatter& rFormatter, sal_uLong nFormat ) const;
461 
462 	// For import filters!
463     void 			AddRecalcMode( formula::ScRecalcMode );
464     /** For import only: set a double result. */
465 	void			SetHybridDouble( double n )     { aResult.SetHybridDouble( n); }
466     /** For import only: set a string result.
467         If for whatever reason you have to use both, SetHybridDouble() and
468         SetHybridString() or SetHybridFormula(), use SetHybridDouble() first
469         for performance reasons.*/
470     void            SetHybridString( const String& r )
471                         { aResult.SetHybridString( r); }
472     /** For import only: set a temporary formula string to be compiled later.
473         If for whatever reason you have to use both, SetHybridDouble() and
474         SetHybridString() or SetHybridFormula(), use SetHybridDouble() first
475         for performance reasons.*/
476     void            SetHybridFormula( const String& r,
477                                     const formula::FormulaGrammar::Grammar eGrammar )
478                         { aResult.SetHybridFormula( r); eTempGrammar = eGrammar; }
479 	void			SetErrCode( sal_uInt16 n );
480 	inline sal_Bool		IsHyperLinkCell() const { return pCode && pCode->IsHyperLink(); }
481 	EditTextObject*		CreateURLObject() ;
482     void            GetURLResult( String& rURL, String& rCellText );
483 
484     /** Determines whether or not the result string contains more than one paragraph */
485     bool            IsMultilineResult();
486 };
487 
488 //			Iterator fuer Referenzen in einer Formelzelle
489 class ScDetectiveRefIter
490 {
491 private:
492 	ScTokenArray* pCode;
493 	ScAddress aPos;
494 public:
495 				ScDetectiveRefIter( ScFormulaCell* pCell );
496 	sal_Bool		GetNextRef( ScRange& rRange );
497 };
498 
499 // ============================================================================
500 
501 #endif
502 
503