/* ==================================================================== Licensed to the Apache Software Foundation (ASF) Under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You Under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed Under the License is distributed on an "AS Is" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations Under the License. ==================================================================== */ namespace HH.WMS.Utils.NPOI.HSSF.Record.Aggregates { using System; using System.Text; using HH.WMS.Utils.NPOI.HSSF.Record; using HH.WMS.Utils.NPOI.SS.Util; using HH.WMS.Utils.NPOI.SS.Formula; using HH.WMS.Utils.NPOI.SS.Formula.PTG; using HH.WMS.Utils.NPOI.Util; /// /// The formula record aggregate is used to join toGether the formula record and it's /// (optional) string record and (optional) Shared Formula Record (template Reads, excel optimization). /// @author Glen Stampoultzis (glens at apache.org) /// [Serializable] public class FormulaRecordAggregate: RecordAggregate, CellValueRecordInterface, IComparable, ICloneable { public const short sid = -2000; private FormulaRecord _formulaRecord; private SharedValueManager _sharedValueManager; /** caches the calculated result of the formula */ private StringRecord _stringRecord; [NonSerialized] private SharedFormulaRecord _sharedFormulaRecord; /// /// Initializes a new instance of the class. /// /// The formula rec. /// The string rec. /// The SVM. public FormulaRecordAggregate(FormulaRecord formulaRec, StringRecord stringRec, SharedValueManager svm) { if (svm == null) { throw new ArgumentException("sfm must not be null"); } if (formulaRec.HasCachedResultString) { if (stringRec == null) { throw new RecordFormatException("Formula record flag is set but String record was not found"); } _stringRecord = stringRec; } else { // Usually stringRec is null here (in agreement with what the formula rec says). // In the case where an extra StringRecord is erroneously present, Excel (2007) // ignores it (see bug 46213). _stringRecord = null; } _formulaRecord = formulaRec; _sharedValueManager = svm; if (formulaRec.IsSharedFormula) { CellReference firstCell = formulaRec.Formula.ExpReference; if (firstCell == null) { HandleMissingSharedFormulaRecord(formulaRec); } else { _sharedFormulaRecord = svm.LinkSharedFormulaRecord(firstCell, this); } } } /** * Should be called by any code which is either deleting this formula cell, or changing * its type. This method gives the aggregate a chance to unlink any shared formula * that may be involved with this cell formula. */ public void NotifyFormulaChanging() { if (_sharedFormulaRecord != null) { _sharedValueManager.Unlink(_sharedFormulaRecord); } } public bool IsPartOfArrayFormula { get { if (_sharedFormulaRecord != null) { return false; } CellReference expRef = _formulaRecord.Formula.ExpReference; ArrayRecord arec = expRef == null ? null : _sharedValueManager.GetArrayRecord(expRef.Row, expRef.Col); return arec != null; } } /// /// called by the class that is responsible for writing this sucker. /// Subclasses should implement this so that their data is passed back in a /// byte array. /// /// offset to begin writing at /// byte array containing instance data. /// number of bytes written public override int Serialize(int offset, byte [] data) { int pos = offset; pos += _formulaRecord.Serialize(pos, data); if (_stringRecord != null) { pos += _stringRecord.Serialize(pos, data); } return pos - offset; } /// /// Visit each of the atomic BIFF records contained in this {@link RecordAggregate} in the order /// that they should be written to file. Implementors may or may not return the actual /// {@link Record}s being used to manage POI's internal implementation. Callers should not /// assume either way, and therefore only attempt to modify those {@link Record}s after cloning /// /// public override void VisitContainedRecords(RecordVisitor rv) { rv.VisitRecord(_formulaRecord); Record sharedFormulaRecord = _sharedValueManager.GetRecordForFirstCell(this); if (sharedFormulaRecord != null) { rv.VisitRecord(sharedFormulaRecord); } if (_formulaRecord.HasCachedResultString && _stringRecord != null) { rv.VisitRecord(_stringRecord); } } /// /// Get the current Serialized size of the record. Should include the sid and recLength (4 bytes). /// /// The size of the record. public override int RecordSize { get { int size = _formulaRecord.RecordSize + (_stringRecord == null ? 0 : _stringRecord.RecordSize); return size; } } /// /// return the non static version of the id for this record. /// /// The sid. public override short Sid { get { return sid; } } /// /// Sometimes the shared formula flag "seems" to be erroneously set (because the corresponding /// SharedFormulaRecord does not exist). Normally this would leave no way of determining /// the Ptg tokens for the formula. However as it turns out in these /// cases, Excel encodes the unshared Ptg tokens in the right place (inside the FormulaRecord). /// So the the only thing that needs to be done is to ignore the erroneous /// shared formula flag. /// /// This method may also be used for setting breakpoints to help diagnose issues regarding the /// abnormally-set 'shared formula' flags. /// /// The formula. private static void HandleMissingSharedFormulaRecord(FormulaRecord formula) { // make sure 'unshared' formula is actually available Ptg firstToken = formula.ParsedExpression[0]; if (firstToken is ExpPtg) { throw new RecordFormatException( "SharedFormulaRecord not found for FormulaRecord with (isSharedFormula=true)"); } // could log an info message here since this is a fairly unusual occurrence. formula.IsSharedFormula = false; // no point leaving the flag erroneously set } /// /// Gets or sets the formula record. /// /// The formula record. public FormulaRecord FormulaRecord { get { return _formulaRecord; } set { this._formulaRecord = value; } } /// /// Gets or sets the string record. /// /// The string record. public StringRecord StringRecord { get { return _stringRecord; } set { this._stringRecord = value; } } public short XFIndex { get{return _formulaRecord.XFIndex;} set{_formulaRecord.XFIndex=value;} } public int Column { get{return _formulaRecord.Column;} set{_formulaRecord.Column=value;} } public int Row { get { return _formulaRecord.Row; } set { _formulaRecord.Row=value; } } public int CompareTo(Object o) { return _formulaRecord.CompareTo(o); } ///// ///// returns whether this cell represents the same cell (NOT VALUE) ///// ///// record to Compare ///// true if the cells are the same cell (positionally), false if not. //public bool IsEqual(CellValueRecordInterface i) //{ // return _formulaRecord.IsEqual(i); //} /// /// Determines whether the specified is equal to the current . /// /// The to compare with the current . /// /// true if the specified is equal to the current ; otherwise, false. /// /// /// The parameter is null. /// public override bool Equals(Object obj) { return _formulaRecord.Equals(obj); } public override int GetHashCode () { return _formulaRecord.GetHashCode (); } /// /// Returns a that represents the current . /// /// /// A that represents the current . /// public override String ToString() { return _formulaRecord.ToString(); } /// /// Gets the string value. /// /// The string value. public String StringValue { get { if (_stringRecord == null) return null; return _stringRecord.String; } } public void SetCachedDoubleResult(double value) { _stringRecord = null; _formulaRecord.Value = value; } /// /// Sets the cached string result. /// /// The value. public void SetCachedStringResult(String value) { // Save the string into a String Record, creating one if required if (_stringRecord == null) { _stringRecord = new StringRecord(); } _stringRecord.String=(value); if (value.Length < 1) { _formulaRecord.SetCachedResultTypeEmptyString(); } else { _formulaRecord.SetCachedResultTypeString(); } } /// /// Sets the cached boolean result. /// /// if set to true [value]. public void SetCachedBooleanResult(bool value) { _stringRecord = null; _formulaRecord.SetCachedResultBoolean(value); } /// /// Sets the cached error result. /// /// The error code. public void SetCachedErrorResult(int errorCode) { _stringRecord = null; _formulaRecord.SetCachedResultErrorCode(errorCode); } #region ICloneable Members public object Clone() { return this; } #endregion public Ptg[] FormulaTokens { get { if (_sharedFormulaRecord != null) { return _sharedFormulaRecord.GetFormulaTokens(_formulaRecord); } CellReference expRef = _formulaRecord.Formula.ExpReference; if (expRef != null) { ArrayRecord arec = _sharedValueManager.GetArrayRecord(expRef.Row, expRef.Col); return arec.FormulaTokens; } return _formulaRecord.ParsedExpression; } } /** * Also checks for a related shared formula and unlinks it if found */ public void SetParsedExpression(Ptg[] ptgs) { NotifyFormulaChanging(); _formulaRecord.ParsedExpression=(ptgs); } public void UnlinkSharedFormula() { SharedFormulaRecord sfr = _sharedFormulaRecord; if (sfr == null) { throw new InvalidOperationException("Formula not linked to shared formula"); } Ptg[] ptgs = sfr.GetFormulaTokens(_formulaRecord); _formulaRecord.SetParsedExpression(ptgs); //Now its not shared! _formulaRecord.SetSharedFormula(false); _sharedFormulaRecord = null; } public CellRangeAddress GetArrayFormulaRange() { if (_sharedFormulaRecord != null) { throw new InvalidOperationException("not an array formula cell."); } CellReference expRef = _formulaRecord.Formula.ExpReference; if (expRef == null) { throw new InvalidOperationException("not an array formula cell."); } ArrayRecord arec = _sharedValueManager.GetArrayRecord(expRef.Row, expRef.Col); if (arec == null) { throw new InvalidOperationException("ArrayRecord was not found for the locator " + expRef.FormatAsString()); } CellRangeAddress8Bit a = arec.Range; return new CellRangeAddress(a.FirstRow, a.LastRow, a.FirstColumn, a.LastColumn); } public void SetArrayFormula(CellRangeAddress r, Ptg[] ptgs) { ArrayRecord arr = new ArrayRecord(HH.WMS.Utils.NPOI.SS.Formula.Formula.Create(ptgs), new CellRangeAddress8Bit(r.FirstRow, r.LastRow, r.FirstColumn, r.LastColumn)); _sharedValueManager.AddArrayRecord(arr); } /** * Removes an array formula * @return the range of the array formula containing the specified cell. Never null */ public CellRangeAddress RemoveArrayFormula(int rowIndex, int columnIndex) { CellRangeAddress8Bit a = _sharedValueManager.RemoveArrayFormula(rowIndex, columnIndex); // at this point FormulaRecordAggregate#isPartOfArrayFormula() should return false _formulaRecord.ParsedExpression = (null); return new CellRangeAddress(a.FirstRow, a.LastRow, a.FirstColumn, a.LastColumn); } } }