[Libreoffice-commits] core.git: 23 commits - sc/inc sc/Library_scfilt.mk sc/qa sc/source

Kohei Yoshida kohei.yoshida at gmail.com
Mon Aug 12 16:45:39 PDT 2013


 sc/Library_scfilt.mk                            |    1 
 sc/inc/column.hxx                               |    5 
 sc/inc/document.hxx                             |    1 
 sc/inc/formulacell.hxx                          |   24 +
 sc/inc/rangenam.hxx                             |    2 
 sc/inc/sharedformula.hxx                        |   20 +
 sc/inc/table.hxx                                |    1 
 sc/inc/tokenarray.hxx                           |    9 
 sc/qa/unit/data/xls/shared-formula.xls          |binary
 sc/qa/unit/filters-test.cxx                     |    9 
 sc/qa/unit/ucalc_sharedformula.cxx              |   23 +
 sc/source/core/data/column.cxx                  |   68 ++++-
 sc/source/core/data/column3.cxx                 |   34 +-
 sc/source/core/data/documen2.cxx                |    8 
 sc/source/core/data/formulacell.cxx             |  301 ++++++++++++++++++++----
 sc/source/core/data/table2.cxx                  |    8 
 sc/source/core/tool/compiler.cxx                |    7 
 sc/source/core/tool/sharedformula.cxx           |   73 ++++-
 sc/source/core/tool/token.cxx                   |  118 +++++++++
 sc/source/filter/excel/excform.cxx              |  141 +++++------
 sc/source/filter/excel/excform8.cxx             |    2 
 sc/source/filter/excel/impop.cxx                |    2 
 sc/source/filter/excel/namebuff.cxx             |   95 +------
 sc/source/filter/excel/read.cxx                 |    2 
 sc/source/filter/excel/xename.cxx               |    4 
 sc/source/filter/excel/xestream.cxx             |    7 
 sc/source/filter/excel/xetable.cxx              |   39 +--
 sc/source/filter/excel/xlformula.cxx            |   13 -
 sc/source/filter/ftools/sharedformulagroups.cxx |   49 +++
 sc/source/filter/inc/excform.hxx                |    2 
 sc/source/filter/inc/formulabuffer.hxx          |  110 +++++---
 sc/source/filter/inc/namebuff.hxx               |   35 +-
 sc/source/filter/inc/orcusinterface.hxx         |    4 
 sc/source/filter/inc/root.hxx                   |    4 
 sc/source/filter/inc/sharedformulagroups.hxx    |   50 +++
 sc/source/filter/inc/sheetdatabuffer.hxx        |    9 
 sc/source/filter/inc/workbookhelper.hxx         |    2 
 sc/source/filter/inc/worksheethelper.hxx        |   13 -
 sc/source/filter/inc/xestream.hxx               |    2 
 sc/source/filter/inc/xetable.hxx                |    3 
 sc/source/filter/inc/xlformula.hxx              |    8 
 sc/source/filter/oox/formulabuffer.cxx          |  183 ++++++++++----
 sc/source/filter/oox/sheetdatabuffer.cxx        |   32 --
 sc/source/filter/oox/sheetdatacontext.cxx       |   18 -
 sc/source/filter/oox/workbookhelper.cxx         |    2 
 sc/source/filter/oox/worksheethelper.cxx        |   11 
 sc/source/filter/orcus/interface.cxx            |  143 ++++++++---
 sc/source/ui/docshell/docfunc.cxx               |    8 
 sc/source/ui/namedlg/namemgrtable.cxx           |    2 
 sc/source/ui/unoobj/cellsuno.cxx                |    2 
 sc/source/ui/unoobj/nameuno.cxx                 |   15 -
 51 files changed, 1189 insertions(+), 535 deletions(-)

New commits:
commit b4038bd494632c5efe1a761cb5bf23e5eebbe065
Author: Kohei Yoshida <kohei.yoshida at gmail.com>
Date:   Mon Aug 12 17:23:30 2013 -0400

    This is clearly a bug. Let's fix it.
    
    Change-Id: I83aa2c108e7d8561d28d76b69a8763a15a20a2bd

diff --git a/sc/inc/sharedformula.hxx b/sc/inc/sharedformula.hxx
index 0b49751..11493e646 100644
--- a/sc/inc/sharedformula.hxx
+++ b/sc/inc/sharedformula.hxx
@@ -34,7 +34,7 @@ public:
         for (++it; it != itEnd; ++it, pPrev = pCur)
         {
             pCur = *it;
-            ScFormulaCell::CompareState eState = pPrev->CompareByTokenArray(*pPrev);
+            ScFormulaCell::CompareState eState = pCur->CompareByTokenArray(*pPrev);
             if (eState == ScFormulaCell::NotEqual)
                 continue;
 
commit 05f86f50a66602761d3f5cff6a9be20994ee2224
Author: Kohei Yoshida <kohei.yoshida at gmail.com>
Date:   Mon Aug 12 16:42:53 2013 -0400

    Ungroup a cell when the group length becomes 1.
    
    Change-Id: Ic656d4837ab1fc5feb4b19765ae427371dfdfe10

diff --git a/sc/source/core/tool/sharedformula.cxx b/sc/source/core/tool/sharedformula.cxx
index 07d9029..6583ac9 100644
--- a/sc/source/core/tool/sharedformula.cxx
+++ b/sc/source/core/tool/sharedformula.cxx
@@ -38,13 +38,25 @@ void SharedFormulaUtil::splitFormulaCellGroup(const CellStoreType::position_type
 
     ScFormulaCellGroupRef xGroup = rTop.GetCellGroup();
 
-    ScFormulaCellGroupRef xGroup2(new ScFormulaCellGroup);
-    xGroup2->mbInvariant = xGroup->mbInvariant;
-    xGroup2->mnStart = nRow;
-    xGroup2->mnLength = xGroup->mnStart + xGroup->mnLength - nRow;
-    xGroup2->mpCode = xGroup->mpCode->Clone();
+    SCROW nLength2 = xGroup->mnStart + xGroup->mnLength - nRow;
+    ScFormulaCellGroupRef xGroup2;
+    if (nLength2 > 1)
+    {
+        xGroup2.reset(new ScFormulaCellGroup);
+        xGroup2->mbInvariant = xGroup->mbInvariant;
+        xGroup2->mnStart = nRow;
+        xGroup2->mnLength = nLength2;
+        xGroup2->mpCode = xGroup->mpCode->Clone();
+    }
 
     xGroup->mnLength = nRow - xGroup->mnStart;
+    if (xGroup->mnLength == 1)
+    {
+        // The top group consists of only one cell. Ungroup this.
+        ScFormulaCellGroupRef xNone;
+        ScFormulaCell& rPrev = *sc::formula_block::at(*aPos.first->data, aPos.second-1);
+        rPrev.SetCellGroup(xNone);
+    }
 
     // Apply the lower group object to the lower cells.
 #if DEBUG_COLUMN_STORAGE
@@ -56,7 +68,7 @@ void SharedFormulaUtil::splitFormulaCellGroup(const CellStoreType::position_type
     }
 #endif
     sc::formula_block::iterator itEnd = it;
-    std::advance(itEnd, xGroup2->mnLength);
+    std::advance(itEnd, nLength2);
     for (; it != itEnd; ++it)
     {
         ScFormulaCell& rCell = **it;
commit f6d37f03cf9c0ff8427612a99c963542e822fcce
Author: Kohei Yoshida <kohei.yoshida at gmail.com>
Date:   Mon Aug 12 16:28:29 2013 -0400

    Fix indentation.
    
    Change-Id: I2caebb42d92bf81e3ba8809a47f833a9379e769d

diff --git a/sc/source/core/tool/sharedformula.cxx b/sc/source/core/tool/sharedformula.cxx
index 9299e33..07d9029 100644
--- a/sc/source/core/tool/sharedformula.cxx
+++ b/sc/source/core/tool/sharedformula.cxx
@@ -48,12 +48,12 @@ void SharedFormulaUtil::splitFormulaCellGroup(const CellStoreType::position_type
 
     // Apply the lower group object to the lower cells.
 #if DEBUG_COLUMN_STORAGE
-        if (xGroup2->mnStart + xGroup2->mnLength > aPos.first->position + aPos.first->size)
-        {
-            cerr << "ScColumn::SplitFormulaCellGroup: Shared formula region goes beyond the formula block. Not good." << endl;
-            cerr.flush();
-            abort();
-        }
+    if (xGroup2->mnStart + xGroup2->mnLength > aPos.first->position + aPos.first->size)
+    {
+        cerr << "ScColumn::SplitFormulaCellGroup: Shared formula region goes beyond the formula block. Not good." << endl;
+        cerr.flush();
+        abort();
+    }
 #endif
     sc::formula_block::iterator itEnd = it;
     std::advance(itEnd, xGroup2->mnLength);
commit 1fd12981565dfc608620252c4abe3fbf8c1bddf2
Author: Kohei Yoshida <kohei.yoshida at gmail.com>
Date:   Mon Aug 12 15:48:50 2013 -0400

    We still need to update cell positions for non-top cells.
    
    Change-Id: If967247ed5d916535e7b52af14b00090b7c9d0d2

diff --git a/sc/inc/formulacell.hxx b/sc/inc/formulacell.hxx
index 3318dd2..2e7c724 100644
--- a/sc/inc/formulacell.hxx
+++ b/sc/inc/formulacell.hxx
@@ -112,6 +112,8 @@ private:
                     };
     void            InterpretTail( ScInterpretTailParameter );
 
+    bool UpdatePosOnShift( const sc::RefUpdateContext& rCxt );
+
     /**
      * Update reference in response to cell insertion or deletion.
      */
diff --git a/sc/source/core/data/formulacell.cxx b/sc/source/core/data/formulacell.cxx
index 1753153..1e120ee 100644
--- a/sc/source/core/data/formulacell.cxx
+++ b/sc/source/core/data/formulacell.cxx
@@ -2173,6 +2173,29 @@ bool ScFormulaCell::HasColRowName() const
     return (pCode->GetNextColRowName() != NULL);
 }
 
+bool ScFormulaCell::UpdatePosOnShift( const sc::RefUpdateContext& rCxt )
+{
+    if (rCxt.meMode != URM_INSDEL)
+        // Just in case...
+        return false;
+
+    if (!rCxt.mnColDelta && !rCxt.mnRowDelta && !rCxt.mnTabDelta)
+        // No movement.
+        return false;
+
+    if (!rCxt.maRange.In(aPos))
+        return false;
+
+    // This formula cell itself is being shifted during cell range
+    // insertion or deletion. Update its position.
+    if (mxGroup && mxGroup->mnStart == aPos.Row())
+        mxGroup->mnStart += rCxt.mnRowDelta;
+
+    aPos.Move(rCxt.mnColDelta, rCxt.mnRowDelta, rCxt.mnTabDelta);
+
+    return true;
+}
+
 namespace {
 
 /**
@@ -2290,17 +2313,7 @@ bool ScFormulaCell::UpdateReferenceOnShift(
     if ( pUndoCellPos )
         aUndoPos = *pUndoCellPos;
     ScAddress aOldPos( aPos );
-
-    if (rCxt.maRange.In(aPos))
-    {
-        // This formula cell itself is being shifted during cell range
-        // insertion or deletion. Update its position.
-        aPos.Move(rCxt.mnColDelta, rCxt.mnRowDelta, rCxt.mnTabDelta);
-        if (mxGroup && mxGroup->mnStart == aOldPos.Row())
-            mxGroup->mnStart += rCxt.mnRowDelta;
-
-        bCellStateChanged = aPos != aOldPos;
-    }
+    bCellStateChanged = UpdatePosOnShift(rCxt);
 
     // Check presence of any references or column row names.
     pCode->Reset();
@@ -2599,8 +2612,19 @@ bool ScFormulaCell::UpdateReference(
         return false;
 
     if (mxGroup && mxGroup->mnStart != aPos.Row())
-        // Update only the top cell in case the cell is part of a formula group.
+    {
+        // This is not a top cell of a formula group. Don't update references.
+
+        switch (rCxt.meMode)
+        {
+            case URM_INSDEL:
+                return UpdatePosOnShift(rCxt);
+            break;
+            default:
+                ;
+        }
         return false;
+    }
 
     switch (rCxt.meMode)
     {
commit 2624788f23d265f0dfeda544f57b9d90a2ab2979
Author: Kohei Yoshida <kohei.yoshida at gmail.com>
Date:   Mon Aug 12 15:23:28 2013 -0400

    Do the splitting of formula groups.
    
    Change-Id: I5a8661895b558b67abc19cdc39de9eb027bc1c34

diff --git a/sc/inc/sharedformula.hxx b/sc/inc/sharedformula.hxx
index 9423384..0b49751 100644
--- a/sc/inc/sharedformula.hxx
+++ b/sc/inc/sharedformula.hxx
@@ -63,7 +63,15 @@ public:
      */
     static void splitFormulaCellGroup(const CellStoreType::position_type& aPos);
 
-    static void splitFormulaCellGroups(CellStoreType& rCells, const std::vector<SCROW>& rBounds);
+    /**
+     * Split existing shared formula ranges at specified row positions.
+     *
+     * @param rCells cell storage container
+     * @param rBounds row positions at which to split existing shared formula
+     *                ranges. Note that this method will directly modify this
+     *                parameter to sort and remove duplicates.
+     */
+    static void splitFormulaCellGroups(CellStoreType& rCells, std::vector<SCROW>& rBounds);
 
     /**
      * See if two specified adjacent formula cells can be merged, and if they
diff --git a/sc/source/core/data/column.cxx b/sc/source/core/data/column.cxx
index a395c78..e4ad8c7 100644
--- a/sc/source/core/data/column.cxx
+++ b/sc/source/core/data/column.cxx
@@ -2364,6 +2364,10 @@ bool ScColumn::UpdateReference( const sc::RefUpdateContext& rCxt, ScDocument* pU
     if (rCxt.meMode == URM_COPY)
         return UpdateReferenceOnCopy(rCxt, pUndoDoc);
 
+    if (IsEmptyData())
+        // Cells in this column are all empty.
+        return false;
+
     std::vector<SCROW> aBounds;
 
     bool bThisColShifted = (rCxt.maRange.aStart.Tab() <= nTab && nTab <= rCxt.maRange.aEnd.Tab() &&
@@ -2387,11 +2391,6 @@ bool ScColumn::UpdateReference( const sc::RefUpdateContext& rCxt, ScDocument* pU
     UpdateRefGroupBoundChecker aBoundChecker(rCxt, aBounds);
     std::for_each(maCells.begin(), maCells.end(), aBoundChecker);
 
-    // Sort and remove duplicates.
-    std::sort(aBounds.begin(), aBounds.end());
-    std::vector<SCROW>::iterator it = std::unique(aBounds.begin(), aBounds.end());
-    aBounds.erase(it, aBounds.end());
-
     // Do the actual splitting.
     sc::SharedFormulaUtil::splitFormulaCellGroups(maCells, aBounds);
 
diff --git a/sc/source/core/tool/sharedformula.cxx b/sc/source/core/tool/sharedformula.cxx
index d9f3a25..9299e33 100644
--- a/sc/source/core/tool/sharedformula.cxx
+++ b/sc/source/core/tool/sharedformula.cxx
@@ -64,9 +64,33 @@ void SharedFormulaUtil::splitFormulaCellGroup(const CellStoreType::position_type
     }
 }
 
-void SharedFormulaUtil::splitFormulaCellGroups(CellStoreType& rCells, const std::vector<SCROW>& rBounds)
+void SharedFormulaUtil::splitFormulaCellGroups(CellStoreType& rCells, std::vector<SCROW>& rBounds)
 {
-    // TODO: Implement this.
+    if (rBounds.empty())
+        return;
+
+    // Sort and remove duplicates.
+    std::sort(rBounds.begin(), rBounds.end());
+    std::vector<SCROW>::iterator it = std::unique(rBounds.begin(), rBounds.end());
+    rBounds.erase(it, rBounds.end());
+
+    it = rBounds.begin();
+    SCROW nRow = *it;
+    CellStoreType::position_type aPos = rCells.position(nRow);
+    if (aPos.first == rCells.end())
+        return;
+
+    splitFormulaCellGroup(aPos);
+    std::vector<SCROW>::iterator itEnd = rBounds.end();
+    for (++it; it != itEnd; ++it)
+    {
+        nRow = *it;
+        aPos = rCells.position(aPos.first, nRow);
+        if (aPos.first == rCells.end())
+            return;
+
+        splitFormulaCellGroup(aPos);
+    }
 }
 
 void SharedFormulaUtil::joinFormulaCells(const CellStoreType::position_type& rPos, ScFormulaCell& rCell1, ScFormulaCell& rCell2)
diff --git a/sc/source/core/tool/token.cxx b/sc/source/core/tool/token.cxx
index 1fbf325..e5627ff 100644
--- a/sc/source/core/tool/token.cxx
+++ b/sc/source/core/tool/token.cxx
@@ -2981,7 +2981,7 @@ void checkBounds(
     SCROW nOffset = rCxt.maRange.aStart.Row() - aAbs.aStart.Row();
     rBounds.push_back(rPos.Row()+nOffset);
     // Ditto.
-    nOffset = rCxt.maRange.aEnd.Row() - aAbs.aStart.Row();
+    nOffset = rCxt.maRange.aEnd.Row() + 1 - aAbs.aStart.Row();
     rBounds.push_back(rPos.Row()+nOffset);
 }
 
commit 30503611efc30ac7a3b09744913f048bf28ef70a
Author: Kohei Yoshida <kohei.yoshida at gmail.com>
Date:   Sat Aug 10 23:31:38 2013 -0400

    Collect all boundaries at which to split the formula group.
    
    Change-Id: Ic78d7a06991b983e625b161f11fbbabce02334f3

diff --git a/sc/inc/formulacell.hxx b/sc/inc/formulacell.hxx
index 0d258a0..3318dd2 100644
--- a/sc/inc/formulacell.hxx
+++ b/sc/inc/formulacell.hxx
@@ -336,6 +336,7 @@ public:
 
     bool IsShared() const;
     bool IsSharedInvariant() const;
+    bool IsSharedTop() const;
     SCROW GetSharedTopRow() const;
     SCROW GetSharedLength() const;
     ScTokenArray* GetSharedCode();
diff --git a/sc/inc/sharedformula.hxx b/sc/inc/sharedformula.hxx
index 232c4bc..9423384 100644
--- a/sc/inc/sharedformula.hxx
+++ b/sc/inc/sharedformula.hxx
@@ -13,6 +13,8 @@
 #include "formulacell.hxx"
 #include "mtvelements.hxx"
 
+#include <vector>
+
 namespace sc {
 
 class SharedFormulaUtil
@@ -61,6 +63,8 @@ public:
      */
     static void splitFormulaCellGroup(const CellStoreType::position_type& aPos);
 
+    static void splitFormulaCellGroups(CellStoreType& rCells, const std::vector<SCROW>& rBounds);
+
     /**
      * See if two specified adjacent formula cells can be merged, and if they
      * can, merge them into the same group.
diff --git a/sc/inc/tokenarray.hxx b/sc/inc/tokenarray.hxx
index 09a9798..00f192d 100644
--- a/sc/inc/tokenarray.hxx
+++ b/sc/inc/tokenarray.hxx
@@ -166,6 +166,9 @@ public:
 
     sc::RefUpdateResult AdjustReferenceOnMovedTab( sc::RefUpdateMoveTabContext& rCxt, const ScAddress& rOldPos );
 
+    void CheckRelativeReferenceBounds(
+        const sc::RefUpdateContext& rCxt, const ScAddress& rPos, SCROW nGroupLen, std::vector<SCROW>& rBounds ) const;
+
 #if DEBUG_FORMULA_COMPILER
     void Dump() const;
 #endif
diff --git a/sc/source/core/data/column.cxx b/sc/source/core/data/column.cxx
index 0171fab..a395c78 100644
--- a/sc/source/core/data/column.cxx
+++ b/sc/source/core/data/column.cxx
@@ -2295,6 +2295,46 @@ public:
     bool isUpdated() const { return mbUpdated; }
 };
 
+class UpdateRefGroupBoundChecker : std::unary_function<sc::CellStoreType::value_type, void>
+{
+    const sc::RefUpdateContext& mrCxt;
+    std::vector<SCROW>& mrBounds;
+public:
+    UpdateRefGroupBoundChecker(const sc::RefUpdateContext& rCxt, std::vector<SCROW>& rBounds) :
+        mrCxt(rCxt), mrBounds(rBounds) {}
+
+    void operator() (const sc::CellStoreType::value_type& node)
+    {
+        if (node.type != sc::element_type_formula)
+            return;
+
+        sc::formula_block::const_iterator it = sc::formula_block::begin(*node.data);
+        sc::formula_block::const_iterator itEnd = sc::formula_block::end(*node.data);
+
+        // Only pick shared formula cells that are the top cells of their
+        // respective shared ranges.
+        for (; it != itEnd; ++it)
+        {
+            const ScFormulaCell& rCell = **it;
+            if (!rCell.IsShared())
+                continue;
+
+            if (rCell.IsSharedTop())
+            {
+                // Check its tokens and record its reference boundaries.
+                const ScTokenArray& rCode = *rCell.GetCode();
+                rCode.CheckRelativeReferenceBounds(
+                    mrCxt, rCell.aPos, rCell.GetSharedLength(), mrBounds);
+
+                // Move to the last cell in the group, to get incremented to
+                // the next cell in the next iteration.
+                size_t nOffsetToLast = rCell.GetSharedLength() - 1;
+                std::advance(it, nOffsetToLast);
+            }
+        }
+    }
+};
+
 }
 
 bool ScColumn::UpdateReferenceOnCopy( const sc::RefUpdateContext& rCxt, ScDocument* pUndoDoc )
@@ -2324,6 +2364,8 @@ bool ScColumn::UpdateReference( const sc::RefUpdateContext& rCxt, ScDocument* pU
     if (rCxt.meMode == URM_COPY)
         return UpdateReferenceOnCopy(rCxt, pUndoDoc);
 
+    std::vector<SCROW> aBounds;
+
     bool bThisColShifted = (rCxt.maRange.aStart.Tab() <= nTab && nTab <= rCxt.maRange.aEnd.Tab() &&
                             rCxt.maRange.aStart.Col() <= nCol && nCol <= rCxt.maRange.aEnd.Col());
     if (bThisColShifted)
@@ -2333,17 +2375,26 @@ bool ScColumn::UpdateReference( const sc::RefUpdateContext& rCxt, ScDocument* pU
         SCROW nSplitPos = rCxt.maRange.aStart.Row();
         if (ValidRow(nSplitPos))
         {
-            sc::CellStoreType::position_type aPos = maCells.position(nSplitPos);
-            sc::SharedFormulaUtil::splitFormulaCellGroup(aPos);
+            aBounds.push_back(nSplitPos);
             nSplitPos = rCxt.maRange.aEnd.Row() + 1;
             if (ValidRow(nSplitPos))
-            {
-                aPos = maCells.position(aPos.first, nSplitPos);
-                sc::SharedFormulaUtil::splitFormulaCellGroup(aPos);
-            }
+                aBounds.push_back(nSplitPos);
         }
     }
 
+    // Check the row positions at which the group must be split per relative
+    // references.
+    UpdateRefGroupBoundChecker aBoundChecker(rCxt, aBounds);
+    std::for_each(maCells.begin(), maCells.end(), aBoundChecker);
+
+    // Sort and remove duplicates.
+    std::sort(aBounds.begin(), aBounds.end());
+    std::vector<SCROW>::iterator it = std::unique(aBounds.begin(), aBounds.end());
+    aBounds.erase(it, aBounds.end());
+
+    // Do the actual splitting.
+    sc::SharedFormulaUtil::splitFormulaCellGroups(maCells, aBounds);
+
     UpdateRefOnNonCopy aHandler(nCol, nTab, rCxt, pUndoDoc);
     sc::ProcessFormula(maCells, aHandler);
     return aHandler.isUpdated();
diff --git a/sc/source/core/data/formulacell.cxx b/sc/source/core/data/formulacell.cxx
index 06fb6dc..1753153 100644
--- a/sc/source/core/data/formulacell.cxx
+++ b/sc/source/core/data/formulacell.cxx
@@ -3824,6 +3824,14 @@ bool ScFormulaCell::IsSharedInvariant() const
     return mxGroup ? mxGroup->mbInvariant : false;
 }
 
+bool ScFormulaCell::IsSharedTop() const
+{
+    if (!mxGroup)
+        return false;
+
+    return mxGroup->mnStart == aPos.Row();
+}
+
 SCROW ScFormulaCell::GetSharedTopRow() const
 {
     return mxGroup ? mxGroup->mnStart : -1;
diff --git a/sc/source/core/tool/sharedformula.cxx b/sc/source/core/tool/sharedformula.cxx
index 3e77934..d9f3a25 100644
--- a/sc/source/core/tool/sharedformula.cxx
+++ b/sc/source/core/tool/sharedformula.cxx
@@ -64,6 +64,11 @@ void SharedFormulaUtil::splitFormulaCellGroup(const CellStoreType::position_type
     }
 }
 
+void SharedFormulaUtil::splitFormulaCellGroups(CellStoreType& rCells, const std::vector<SCROW>& rBounds)
+{
+    // TODO: Implement this.
+}
+
 void SharedFormulaUtil::joinFormulaCells(const CellStoreType::position_type& rPos, ScFormulaCell& rCell1, ScFormulaCell& rCell2)
 {
     ScFormulaCell::CompareState eState = rCell1.CompareByTokenArray(rCell2);
diff --git a/sc/source/core/tool/token.cxx b/sc/source/core/tool/token.cxx
index d74182d..1fbf325 100644
--- a/sc/source/core/tool/token.cxx
+++ b/sc/source/core/tool/token.cxx
@@ -2934,6 +2934,88 @@ sc::RefUpdateResult ScTokenArray::AdjustReferenceOnMovedTab( sc::RefUpdateMoveTa
     return aRes;
 }
 
+namespace {
+
+void checkBounds(
+    const sc::RefUpdateContext& rCxt, const ScAddress& rPos, SCROW nGroupLen,
+    const ScSingleRefData& rRef, std::vector<SCROW>& rBounds)
+{
+    if (!rRef.IsRowRel())
+        return;
+
+    ScRange aAbs(rRef.toAbs(rPos));
+    aAbs.aEnd.IncRow(nGroupLen-1);
+    if (!rCxt.maRange.Intersects(aAbs))
+        return;
+
+    // Get the boundary row positions.
+    if (aAbs.aEnd.Row() < rCxt.maRange.aStart.Row())
+        // No intersections.
+        return;
+
+    if (aAbs.aEnd.Row() <= rCxt.maRange.aEnd.Row())
+    {
+        //    +-+ <---- top
+        //    | |
+        // +--+-+--+ <---- boundary row position
+        // |  | |  |
+        // |  +-+  |
+        // +-------+
+
+        // Add offset from the reference top to the cell position.
+        SCROW nOffset = rCxt.maRange.aStart.Row() - aAbs.aStart.Row();
+        rBounds.push_back(rPos.Row()+nOffset);
+        return;
+    }
+
+    //    +-+ <---- top
+    //    | |
+    // +--+-+--+ <---- boundary row position
+    // |  | |  |
+    // |  | |  |
+    // +--+-+--+ <---- boundary row position
+    //    | |
+    //    +-+
+
+    // Add offset from the reference top to the cell position.
+    SCROW nOffset = rCxt.maRange.aStart.Row() - aAbs.aStart.Row();
+    rBounds.push_back(rPos.Row()+nOffset);
+    // Ditto.
+    nOffset = rCxt.maRange.aEnd.Row() - aAbs.aStart.Row();
+    rBounds.push_back(rPos.Row()+nOffset);
+}
+
+}
+
+void ScTokenArray::CheckRelativeReferenceBounds(
+    const sc::RefUpdateContext& rCxt, const ScAddress& rPos, SCROW nGroupLen, std::vector<SCROW>& rBounds ) const
+{
+    FormulaToken** p = pCode;
+    FormulaToken** pEnd = p + static_cast<size_t>(nLen);
+    for (; p != pEnd; ++p)
+    {
+        switch ((*p)->GetType())
+        {
+            case svSingleRef:
+            {
+                ScToken* pToken = static_cast<ScToken*>(*p);
+                checkBounds(rCxt, rPos, nGroupLen, pToken->GetSingleRef(), rBounds);
+            }
+            break;
+            case svDoubleRef:
+            {
+                ScToken* pToken = static_cast<ScToken*>(*p);
+                const ScComplexRefData& rRef = pToken->GetDoubleRef();
+                checkBounds(rCxt, rPos, nGroupLen, rRef.Ref1, rBounds);
+                checkBounds(rCxt, rPos, nGroupLen, rRef.Ref2, rBounds);
+            }
+            break;
+            default:
+                ;
+        }
+    }
+}
+
 #if DEBUG_FORMULA_COMPILER
 void ScTokenArray::Dump() const
 {
commit bbb2d8c660b515c98624a41a39ffe94d3a7ecc00
Author: Kohei Yoshida <kohei.yoshida at gmail.com>
Date:   Fri Aug 9 16:41:22 2013 -0400

    If the formula cell is grouped, update reference only on the top cell.
    
    Change-Id: I5e2e9db621a61deba39a46962e0ca877235d7c90

diff --git a/sc/source/core/data/formulacell.cxx b/sc/source/core/data/formulacell.cxx
index c87b045..06fb6dc 100644
--- a/sc/source/core/data/formulacell.cxx
+++ b/sc/source/core/data/formulacell.cxx
@@ -2598,6 +2598,10 @@ bool ScFormulaCell::UpdateReference(
     if (pDocument->IsClipOrUndo())
         return false;
 
+    if (mxGroup && mxGroup->mnStart != aPos.Row())
+        // Update only the top cell in case the cell is part of a formula group.
+        return false;
+
     switch (rCxt.meMode)
     {
         case URM_INSDEL:
commit a592b81558c41e71c0f139d86489b163148ea8b7
Author: Kohei Yoshida <kohei.yoshida at gmail.com>
Date:   Fri Aug 9 12:09:44 2013 -0400

    Export shared formulas to xls, from the new shared formula in the core.
    
    Turns out we don't export shared formulas to xlsx, so no work is needed
    there.
    
    Change-Id: I85604f3b80c95c5b6179bbdac41e758c5de7854a

diff --git a/sc/source/filter/excel/xetable.cxx b/sc/source/filter/excel/xetable.cxx
index 99313ea..d7b6499 100644
--- a/sc/source/filter/excel/xetable.cxx
+++ b/sc/source/filter/excel/xetable.cxx
@@ -207,28 +207,29 @@ XclExpShrfmlaBuffer::XclExpShrfmlaBuffer( const XclExpRoot& rRoot ) :
 }
 
 XclExpShrfmlaRef XclExpShrfmlaBuffer::CreateOrExtendShrfmla(
-        const ScTokenArray& rScTokArr, const ScAddress& rScPos )
+    const ScFormulaCell& rScCell, const ScAddress& rScPos )
 {
     XclExpShrfmlaRef xRec;
-    if( const ScTokenArray* pShrdScTokArr = XclTokenArrayHelper::GetSharedFormula( GetRoot(), rScTokArr ) )
+    const ScTokenArray* pShrdScTokArr = rScCell.GetSharedCode();
+    if (!pShrdScTokArr)
+        // This formula cell is not shared formula cell.
+        return xRec;
+
+    XclExpShrfmlaMap::iterator aIt = maRecMap.find( pShrdScTokArr );
+    if( aIt == maRecMap.end() )
     {
-        XclExpShrfmlaMap::iterator aIt = maRecMap.find( pShrdScTokArr );
-        if( aIt == maRecMap.end() )
-        {
-            // create a new record
-            XclTokenArrayRef xTokArr = GetFormulaCompiler().CreateFormula( EXC_FMLATYPE_SHARED, *pShrdScTokArr, &rScPos );
-            xRec.reset( new XclExpShrfmla( xTokArr, rScPos ) );
-            maRecMap[ pShrdScTokArr ] = xRec;
-        }
-        else
-        {
-            // extend existing record
-            OSL_ENSURE( aIt->second, "XclExpShrfmlaBuffer::CreateOrExtendShrfmla - missing record" );
-            xRec = aIt->second;
-            xRec->ExtendRange( rScPos );
-        }
+        // create a new record
+        XclTokenArrayRef xTokArr = GetFormulaCompiler().CreateFormula( EXC_FMLATYPE_SHARED, *pShrdScTokArr, &rScPos );
+        xRec.reset( new XclExpShrfmla( xTokArr, rScPos ) );
+        maRecMap[ pShrdScTokArr ] = xRec;
+    }
+    else
+    {
+        // extend existing record
+        OSL_ENSURE( aIt->second, "XclExpShrfmlaBuffer::CreateOrExtendShrfmla - missing record" );
+        xRec = aIt->second;
+        xRec->ExtendRange( rScPos );
     }
-    return xRec;
 }
 
 // Multiple operations ========================================================
@@ -851,7 +852,7 @@ XclExpFormulaCell::XclExpFormulaCell(
 
     // no matrix found - try to create shared formula
     if( !mxAddRec )
-        mxAddRec = rShrfmlaBfr.CreateOrExtendShrfmla( rScTokArr, aScPos );
+        mxAddRec = rShrfmlaBfr.CreateOrExtendShrfmla(mrScFmlaCell, aScPos);
 
     // no shared formula found - create a simple cell formula
     if( !mxAddRec )
diff --git a/sc/source/filter/excel/xlformula.cxx b/sc/source/filter/excel/xlformula.cxx
index 2eff911..fa2bb20 100644
--- a/sc/source/filter/excel/xlformula.cxx
+++ b/sc/source/filter/excel/xlformula.cxx
@@ -763,13 +763,6 @@ void XclTokenArrayHelper::ConvertStringToList( ScTokenArray& rScTokArr, sal_Unic
     }
 }
 
-// shared formulas ------------------------------------------------------------
-
-const ScTokenArray* XclTokenArrayHelper::GetSharedFormula( const XclRoot& /*rRoot*/, const ScTokenArray& /*rScTokArr*/ )
-{
-    return NULL;
-}
-
 // multiple operations --------------------------------------------------------
 
 namespace {
diff --git a/sc/source/filter/inc/xetable.hxx b/sc/source/filter/inc/xetable.hxx
index 533d2ec..0e47052 100644
--- a/sc/source/filter/inc/xetable.hxx
+++ b/sc/source/filter/inc/xetable.hxx
@@ -189,8 +189,7 @@ public:
             function updates its cell range to include the passed cell position,
             if there is a SHRFMLA record for the passed token array; otherwise
             this function creates and returns a new SHRFMLA record. */
-    XclExpShrfmlaRef    CreateOrExtendShrfmla(
-                            const ScTokenArray& rScTokArr, const ScAddress& rScPos );
+    XclExpShrfmlaRef CreateOrExtendShrfmla( const ScFormulaCell& rScCell, const ScAddress& rScPos );
 
 private:
     typedef ::std::map< const ScTokenArray*, XclExpShrfmlaRef > XclExpShrfmlaMap;
diff --git a/sc/source/filter/inc/xlformula.hxx b/sc/source/filter/inc/xlformula.hxx
index fdf395e..0a90e08 100644
--- a/sc/source/filter/inc/xlformula.hxx
+++ b/sc/source/filter/inc/xlformula.hxx
@@ -523,14 +523,6 @@ public:
         @param bTrimLeadingSpaces  true = remove leading spaces from each token. */
     static void         ConvertStringToList( ScTokenArray& rScTokArr, sal_Unicode cStringSep, bool bTrimLeadingSpaces );
 
-    // shared formulas --------------------------------------------------------
-
-    /** Tries to extract the definition of a shared formula from the passed token array.
-        @descr  Shared formulas are stored as hidden defined names in Calc. This
-        function looks if the passed token array consists of the reference to
-        such a hidden defined name and returns its definition on success. */
-    static const ScTokenArray* GetSharedFormula( const XclRoot& rRoot, const ScTokenArray& rScTokArr );
-
     // multiple operations ----------------------------------------------------
 
     /** Parses the passed formula and tries to extract references of a multiple operation.
commit b26fd34f8aa9589dd66a8f4c5b0e6771a4529c03
Author: Kohei Yoshida <kohei.yoshida at gmail.com>
Date:   Thu Aug 8 07:52:45 2013 -0400

    Fix the (Windows) build. No idea how this was buildable on Linux.
    
    Change-Id: I9c0701b1b8f30c36f45bbee0d95e92a59f9891fe

diff --git a/sc/source/filter/oox/formulabuffer.cxx b/sc/source/filter/oox/formulabuffer.cxx
index 59518bc..e4277c0 100644
--- a/sc/source/filter/oox/formulabuffer.cxx
+++ b/sc/source/filter/oox/formulabuffer.cxx
@@ -33,12 +33,12 @@ using namespace ::com::sun::star::container;
 
 namespace oox { namespace xls {
 
-FormulaBuffer::FormulaBuffer::SharedFormulaEntry::SharedFormulaEntry(
+FormulaBuffer::SharedFormulaEntry::SharedFormulaEntry(
     const table::CellAddress& rAddr, const table::CellRangeAddress& rRange,
     const OUString& rTokenStr, sal_Int32 nSharedId ) :
     maAddress(rAddr), maRange(rRange), maTokenStr(rTokenStr), mnSharedId(nSharedId) {}
 
-FormulaBuffer::FormulaBuffer::SharedFormulaDesc::SharedFormulaDesc(
+FormulaBuffer::SharedFormulaDesc::SharedFormulaDesc(
     const com::sun::star::table::CellAddress& rAddr, sal_Int32 nSharedId,
     const OUString& rCellValue, sal_Int32 nValueType ) :
     maAddress(rAddr), mnSharedId(nSharedId), maCellValue(rCellValue), mnValueType(nValueType) {}
commit 6f8b0d419b99a02050a9dd8bdf04a6c86a48fe61
Author: Kohei Yoshida <kohei.yoshida at gmail.com>
Date:   Thu Aug 8 00:27:15 2013 -0400

    Detect self-referencing groups, and disable group-calculation.
    
    And re-enable group-calculation on named ranges.
    
    Change-Id: I4957ff05bac23bd266bbc96fe5619ad5f0a65688

diff --git a/sc/source/core/data/formulacell.cxx b/sc/source/core/data/formulacell.cxx
index fd103bc..c87b045 100644
--- a/sc/source/core/data/formulacell.cxx
+++ b/sc/source/core/data/formulacell.cxx
@@ -3279,6 +3279,49 @@ class GroupTokenConverter
     ScDocument& mrDoc;
     ScFormulaCell& mrCell;
     const ScAddress& mrPos;
+
+    bool isSelfReferenceRelative(const ScAddress& rRefPos, SCROW nRelRow)
+    {
+        if (rRefPos.Col() != mrPos.Col())
+            return false;
+
+        SCROW nLen = mrCell.GetCellGroup()->mnLength;
+        SCROW nEndRow = mrPos.Row() + nLen - 1;
+
+        if (nRelRow < 0)
+        {
+            SCROW nTest = nEndRow;
+            nTest += nRelRow;
+            if (nTest >= mrPos.Row())
+                return true;
+        }
+        else if (nRelRow > 0)
+        {
+            SCROW nTest = mrPos.Row(); // top row.
+            nTest += nRelRow;
+            if (nTest <= nEndRow)
+                return true;
+        }
+
+        return false;
+    }
+
+    bool isSelfReferenceAbsolute(const ScAddress& rRefPos)
+    {
+        if (rRefPos.Col() != mrPos.Col())
+            return false;
+
+        SCROW nLen = mrCell.GetCellGroup()->mnLength;
+        SCROW nEndRow = mrPos.Row() + nLen - 1;
+
+        if (rRefPos.Row() < mrPos.Row())
+            return false;
+
+        if (rRefPos.Row() > nEndRow)
+            return false;
+
+        return true;
+    }
 public:
     GroupTokenConverter(sc::FormulaGroupContext& rCxt, ScTokenArray& rGroupTokens, ScDocument& rDoc, ScFormulaCell& rCell, const ScAddress& rPos) :
         mrCxt(rCxt), mrGroupTokens(rGroupTokens), mrDoc(rDoc), mrCell(rCell), mrPos(rPos) {}
@@ -3302,6 +3345,7 @@ public:
             // absolute reference state for row directions.
 
             const ScToken* pToken = static_cast<const ScToken*>(p);
+            SCROW nLen = mrCell.GetCellGroup()->mnLength;
             switch (pToken->GetType())
             {
                 case svSingleRef:
@@ -3310,20 +3354,26 @@ public:
                     ScAddress aRefPos = aRef.toAbs(mrPos);
                     if (aRef.IsRowRel())
                     {
+                        if (isSelfReferenceRelative(aRefPos, aRef.Row()))
+                            return false;
+
                         // Fetch double array guarantees that the length of the
                         // returned array equals or greater than the requested
                         // length.
 
-                        const double* pArray = mrDoc.FetchDoubleArray(mrCxt, aRefPos, mrCell.GetCellGroup()->mnLength);
+                        const double* pArray = mrDoc.FetchDoubleArray(mrCxt, aRefPos, nLen);
                         if (!pArray)
                             return false;
 
-                        formula::SingleVectorRefToken aTok(pArray, mrCell.GetCellGroup()->mnLength);
+                        formula::SingleVectorRefToken aTok(pArray, nLen);
                         mrGroupTokens.AddToken(aTok);
                     }
                     else
                     {
                         // Absolute row reference.
+                        if (isSelfReferenceAbsolute(aRefPos))
+                            return false;
+
                         formula::FormulaTokenRef pNewToken = mrDoc.ResolveStaticReference(aRefPos);
                         if (!pNewToken)
                             return false;
@@ -3337,6 +3387,23 @@ public:
                     ScComplexRefData aRef = pToken->GetDoubleRef();
                     ScRange aAbs = aRef.toAbs(mrCell.aPos);
 
+                    // Check for self reference.
+                    if (aRef.Ref1.IsRowRel())
+                    {
+                        if (isSelfReferenceRelative(aAbs.aStart, aRef.Ref1.Row()))
+                            return false;
+                    }
+                    else if (isSelfReferenceAbsolute(aAbs.aStart))
+                        return false;
+
+                    if (aRef.Ref2.IsRowRel())
+                    {
+                        if (isSelfReferenceRelative(aAbs.aEnd, aRef.Ref2.Row()))
+                            return false;
+                    }
+                    else if (isSelfReferenceAbsolute(aAbs.aEnd))
+                        return false;
+
                     // Row reference is relative.
                     bool bAbsFirst = !aRef.Ref1.IsRowRel();
                     bool bAbsLast = !aRef.Ref2.IsRowRel();
@@ -3344,7 +3411,7 @@ public:
                     size_t nCols = aAbs.aEnd.Col() - aAbs.aStart.Col() + 1;
                     std::vector<const double*> aArrays;
                     aArrays.reserve(nCols);
-                    SCROW nArrayLength = mrCell.GetCellGroup()->mnLength;
+                    SCROW nArrayLength = nLen;
                     SCROW nRefRowSize = aAbs.aEnd.Row() - aAbs.aStart.Row() + 1;
                     if (!bAbsLast)
                     {
@@ -3366,6 +3433,32 @@ public:
                     mrGroupTokens.AddToken(aTok);
                 }
                 break;
+                case svIndex:
+                {
+                    // Named range.
+                    ScRangeName* pNames = mrDoc.GetRangeName();
+                    if (!pNames)
+                        // This should never fail.
+                        return false;
+
+                    ScRangeData* pRange = pNames->findByIndex(p->GetIndex());
+                    if (!pRange)
+                        // No named range exists by that index.
+                        return false;
+
+                    ScTokenArray* pNamedTokens = pRange->GetCode();
+                    if (!pNamedTokens)
+                        // This named range is empty.
+                        return false;
+
+                    mrGroupTokens.AddOpCode(ocOpen);
+
+                    if (!convert(*pNamedTokens))
+                        return false;
+
+                    mrGroupTokens.AddOpCode(ocClose);
+                }
+                break;
                 default:
                     mrGroupTokens.AddToken(*pToken);
             }
diff --git a/sc/source/core/tool/token.cxx b/sc/source/core/tool/token.cxx
index 9f58380..d74182d 100644
--- a/sc/source/core/tool/token.cxx
+++ b/sc/source/core/tool/token.cxx
@@ -1347,9 +1347,6 @@ void ScTokenArray::CheckToken( const FormulaToken& r )
                 ;
         }
     }
-
-    if (eOp == ocName)
-        meVectorState = FormulaVectorDisabled;
 }
 
 bool ScTokenArray::ImplGetReference( ScRange& rRange, const ScAddress& rPos, bool bValidOnly ) const
commit 0c7dd40e63bd6aa401fb731f9ac9daeb30c6e8f1
Author: Kohei Yoshida <kohei.yoshida at gmail.com>
Date:   Wed Aug 7 23:58:32 2013 -0400

    Fix import of negative relative row reference from xls.
    
    Change-Id: Ibaa325396a8a06c45cf59af9809ed5cbff6d10d0

diff --git a/sc/source/filter/excel/excform8.cxx b/sc/source/filter/excel/excform8.cxx
index 35de70f..043b3f4 100644
--- a/sc/source/filter/excel/excform8.cxx
+++ b/sc/source/filter/excel/excform8.cxx
@@ -1417,7 +1417,7 @@ void ExcelToSc8::ExcRelToScRel8( sal_uInt16 nRow, sal_uInt16 nC, ScSingleRefData
 
         // R O W
         if( bRowRel )
-            rSRD.SetRelRow(nRow);
+            rSRD.SetRelRow(static_cast<sal_Int16>(nRow));
         else
             rSRD.SetAbsRow(std::min( static_cast<SCROW>(nRow), MAXROW));
     }
commit 6775874b54abcd625e220f9c7401cb04050135b4
Author: Kohei Yoshida <kohei.yoshida at gmail.com>
Date:   Wed Aug 7 23:09:43 2013 -0400

    Disable vectorization on named ranges for now.
    
    Change-Id: Ibc10d5eb9afff6062106c952aa2e7d3f9cb58100

diff --git a/sc/source/core/data/formulacell.cxx b/sc/source/core/data/formulacell.cxx
index 4a05c4c..fd103bc 100644
--- a/sc/source/core/data/formulacell.cxx
+++ b/sc/source/core/data/formulacell.cxx
@@ -3366,32 +3366,6 @@ public:
                     mrGroupTokens.AddToken(aTok);
                 }
                 break;
-                case svIndex:
-                {
-                    // Named range.
-                    ScRangeName* pNames = mrDoc.GetRangeName();
-                    if (!pNames)
-                        // This should never fail.
-                        return false;
-
-                    ScRangeData* pRange = pNames->findByIndex(p->GetIndex());
-                    if (!pRange)
-                        // No named range exists by that index.
-                        return false;
-
-                    ScTokenArray* pNamedTokens = pRange->GetCode();
-                    if (!pNamedTokens)
-                        // This named range is empty.
-                        return false;
-
-                    mrGroupTokens.AddOpCode(ocOpen);
-
-                    if (!convert(*pNamedTokens))
-                        return false;
-
-                    mrGroupTokens.AddOpCode(ocClose);
-                }
-                break;
                 default:
                     mrGroupTokens.AddToken(*pToken);
             }
diff --git a/sc/source/core/tool/token.cxx b/sc/source/core/tool/token.cxx
index d74182d..9f58380 100644
--- a/sc/source/core/tool/token.cxx
+++ b/sc/source/core/tool/token.cxx
@@ -1347,6 +1347,9 @@ void ScTokenArray::CheckToken( const FormulaToken& r )
                 ;
         }
     }
+
+    if (eOp == ocName)
+        meVectorState = FormulaVectorDisabled;
 }
 
 bool ScTokenArray::ImplGetReference( ScRange& rRange, const ScAddress& rPos, bool bValidOnly ) const
commit cccf0fe7a6d8f82e966c320a13875d67fdb911f6
Author: Kohei Yoshida <kohei.yoshida at gmail.com>
Date:   Wed Aug 7 22:59:23 2013 -0400

    Uncomment this.
    
    Change-Id: I628c826905d0c1074fbc5c12e821c0efd6489bbf

diff --git a/sc/source/core/data/formulacell.cxx b/sc/source/core/data/formulacell.cxx
index d6254c2..4a05c4c 100644
--- a/sc/source/core/data/formulacell.cxx
+++ b/sc/source/core/data/formulacell.cxx
@@ -3410,7 +3410,7 @@ bool ScFormulaCell::InterpretFormulaGroup()
 
     // Re-build formulae groups if necessary - ideally this is done at
     // import / insert / delete etc. and is integral to the data structures
-//  pDocument->RebuildFormulaGroups();
+    pDocument->RebuildFormulaGroups();
 
     if (!mxGroup || !pCode)
         return false;
commit f3a632c8753079a954187ea0f60f9606fdb3fe27
Author: Kohei Yoshida <kohei.yoshida at gmail.com>
Date:   Wed Aug 7 19:04:53 2013 -0400

    No more RT_SHARED and RT_SHAREDMOD named range types.
    
    Change-Id: Ic8d98b62747ae29cc968ce926e2ae42537023840

diff --git a/sc/inc/rangenam.hxx b/sc/inc/rangenam.hxx
index 4a56ea1..e2731b5 100644
--- a/sc/inc/rangenam.hxx
+++ b/sc/inc/rangenam.hxx
@@ -51,8 +51,6 @@ typedef sal_uInt16 RangeType;
 #define RT_ABSAREA          ((RangeType)0x0020)
 #define RT_REFAREA          ((RangeType)0x0040)
 #define RT_ABSPOS           ((RangeType)0x0080)
-#define RT_SHARED           ((RangeType)0x0100)
-#define RT_SHAREDMOD        ((RangeType)0x0200)
 
 class ScRangeData
 {
diff --git a/sc/source/core/data/formulacell.cxx b/sc/source/core/data/formulacell.cxx
index c3ab5cd..d6254c2 100644
--- a/sc/source/core/data/formulacell.cxx
+++ b/sc/source/core/data/formulacell.cxx
@@ -2825,8 +2825,6 @@ void ScFormulaCell::UpdateTranspose( const ScRange& rSource, const ScAddress& rD
             {
                 if (pName->IsModified())
                     bRefChanged = true;
-                if (pName->HasType(RT_SHAREDMOD))
-                    pShared = pName;
             }
         }
         else if( t->GetType() != svIndex )
@@ -2902,8 +2900,6 @@ void ScFormulaCell::UpdateGrow( const ScRange& rArea, SCCOL nGrowX, SCROW nGrowY
             {
                 if (pName->IsModified())
                     bRefChanged = true;
-                if (pName->HasType(RT_SHAREDMOD))
-                    pShared = pName;
             }
         }
         else if( t->GetType() != svIndex )
diff --git a/sc/source/core/tool/compiler.cxx b/sc/source/core/tool/compiler.cxx
index 6391690..547daa6 100644
--- a/sc/source/core/tool/compiler.cxx
+++ b/sc/source/core/tool/compiler.cxx
@@ -4302,12 +4302,7 @@ void ScCompiler::CreateStringFromIndex(OUStringBuffer& rBuffer,FormulaToken* _pT
         {
             ScRangeData* pData = GetRangeData( *_pTokenP);
             if (pData)
-            {
-                if (pData->HasType(RT_SHARED))
-                    pData->UpdateSymbol( aBuffer, aPos, GetGrammar());
-                else
-                    aBuffer.append(pData->GetName());
-            }
+                aBuffer.append(pData->GetName());
         }
         break;
         case ocDBArea:
diff --git a/sc/source/filter/excel/xename.cxx b/sc/source/filter/excel/xename.cxx
index 276624c..54f2e8d 100644
--- a/sc/source/filter/excel/xename.cxx
+++ b/sc/source/filter/excel/xename.cxx
@@ -657,7 +657,7 @@ void XclExpNameManagerImpl::CreateUserNames()
     for (; itr != itrEnd; ++itr)
     {
         // skip definitions of shared formulas
-        if (!itr->second->HasType(RT_SHARED) && !FindNamedExpIndex(SCTAB_GLOBAL, itr->second->GetIndex()))
+        if (!FindNamedExpIndex(SCTAB_GLOBAL, itr->second->GetIndex()))
             CreateName(SCTAB_GLOBAL, *itr->second);
     }
     //look at every sheet for local range names
@@ -670,7 +670,7 @@ void XclExpNameManagerImpl::CreateUserNames()
         for (; itr != itrEnd; ++itr)
         {
             // skip definitions of shared formulas
-            if (!itr->second->HasType(RT_SHARED) && !FindNamedExpIndex(tabIt->first, itr->second->GetIndex()))
+            if (!FindNamedExpIndex(tabIt->first, itr->second->GetIndex()))
                 CreateName(tabIt->first, *itr->second);
         }
     }
diff --git a/sc/source/filter/excel/xlformula.cxx b/sc/source/filter/excel/xlformula.cxx
index 94d9594..2eff911 100644
--- a/sc/source/filter/excel/xlformula.cxx
+++ b/sc/source/filter/excel/xlformula.cxx
@@ -765,15 +765,9 @@ void XclTokenArrayHelper::ConvertStringToList( ScTokenArray& rScTokArr, sal_Unic
 
 // shared formulas ------------------------------------------------------------
 
-const ScTokenArray* XclTokenArrayHelper::GetSharedFormula( const XclRoot& rRoot, const ScTokenArray& rScTokArr )
-{
-    if( rScTokArr.GetLen() == 1 )
-        if( const FormulaToken* pScToken = rScTokArr.GetArray()[ 0 ] )
-            if( pScToken->GetOpCode() == ocName )
-                if( ScRangeData* pData = rRoot.GetNamedRanges().findByIndex( pScToken->GetIndex() ) )
-                    if( pData->HasType( RT_SHARED ) )
-                        return pData->GetCode();
-    return 0;
+const ScTokenArray* XclTokenArrayHelper::GetSharedFormula( const XclRoot& /*rRoot*/, const ScTokenArray& /*rScTokArr*/ )
+{
+    return NULL;
 }
 
 // multiple operations --------------------------------------------------------
diff --git a/sc/source/ui/docshell/docfunc.cxx b/sc/source/ui/docshell/docfunc.cxx
index 9ff21c7..5c1b7a6 100644
--- a/sc/source/ui/docshell/docfunc.cxx
+++ b/sc/source/ui/docshell/docfunc.cxx
@@ -5073,7 +5073,7 @@ sal_Bool ScDocFunc::InsertNameList( const ScAddress& rStartPos, sal_Bool bApi )
     for (ScRangeName::iterator itr = itrLocalBeg; itr != itrLocalEnd; ++itr)
     {
         const ScRangeData& r = *itr->second;
-        if (!r.HasType(RT_DATABASE) && !r.HasType(RT_SHARED))
+        if (!r.HasType(RT_DATABASE))
             ++nValidCount;
     }
     ScRangeName* pList = pDoc->GetRangeName();
@@ -5081,7 +5081,7 @@ sal_Bool ScDocFunc::InsertNameList( const ScAddress& rStartPos, sal_Bool bApi )
     for (ScRangeName::iterator itr = itrBeg; itr != itrEnd; ++itr)
     {
         const ScRangeData& r = *itr->second;
-        if (!r.HasType(RT_DATABASE) && !r.HasType(RT_SHARED) && !pLocalList->findByUpperName(r.GetUpperName()))
+        if (!r.HasType(RT_DATABASE) && !pLocalList->findByUpperName(r.GetUpperName()))
             ++nValidCount;
     }
 
@@ -5110,13 +5110,13 @@ sal_Bool ScDocFunc::InsertNameList( const ScAddress& rStartPos, sal_Bool bApi )
             for (ScRangeName::iterator itr = itrLocalBeg; itr != itrLocalEnd; ++itr)
             {
                 ScRangeData& r = *itr->second;
-                if (!r.HasType(RT_DATABASE) && !r.HasType(RT_SHARED))
+                if (!r.HasType(RT_DATABASE))
                     ppSortArray[j++] = &r;
             }
             for (ScRangeName::iterator itr = itrBeg; itr != itrEnd; ++itr)
             {
                 ScRangeData& r = *itr->second;
-                if (!r.HasType(RT_DATABASE) && !r.HasType(RT_SHARED) && !pLocalList->findByUpperName(itr->first))
+                if (!r.HasType(RT_DATABASE) && !pLocalList->findByUpperName(itr->first))
                     ppSortArray[j++] = &r;
             }
 #ifndef ICC
diff --git a/sc/source/ui/namedlg/namemgrtable.cxx b/sc/source/ui/namedlg/namemgrtable.cxx
index fd315c0..0fee2be 100644
--- a/sc/source/ui/namedlg/namemgrtable.cxx
+++ b/sc/source/ui/namedlg/namemgrtable.cxx
@@ -143,7 +143,7 @@ void ScRangeManagerTable::Init()
         for (ScRangeName::const_iterator it = pLocalRangeName->begin();
                 it != pLocalRangeName->end(); ++it)
         {
-            if (!it->second->HasType(RT_DATABASE) && !it->second->HasType(RT_SHARED))
+            if (!it->second->HasType(RT_DATABASE))
             {
                 aLine.aName = it->second->GetName();
                 addEntry(aLine, false);
diff --git a/sc/source/ui/unoobj/nameuno.cxx b/sc/source/ui/unoobj/nameuno.cxx
index 0ec46ba..ae7a342 100644
--- a/sc/source/ui/unoobj/nameuno.cxx
+++ b/sc/source/ui/unoobj/nameuno.cxx
@@ -82,7 +82,7 @@ static bool lcl_UserVisibleName(const ScRangeData& rData)
 {
     //! als Methode an ScRangeData
 
-    return !rData.HasType(RT_DATABASE) && !rData.HasType(RT_SHARED);
+    return !rData.HasType(RT_DATABASE);
 }
 
 ScNamedRangeObj::ScNamedRangeObj( rtl::Reference< ScNamedRangesObj > xParent, ScDocShell* pDocSh, const String& rNm, Reference<container::XNamed> xSheet):
@@ -378,7 +378,7 @@ uno::Reference<beans::XPropertySetInfo> SAL_CALL ScNamedRangeObj::getPropertySet
 }
 
 void SAL_CALL ScNamedRangeObj::setPropertyValue(
-                        const OUString& rPropertyName, const uno::Any& aValue )
+                        const OUString& rPropertyName, const uno::Any& /*aValue*/ )
                 throw(beans::UnknownPropertyException, beans::PropertyVetoException,
                         lang::IllegalArgumentException, lang::WrappedTargetException,
                         uno::RuntimeException)
@@ -386,12 +386,7 @@ void SAL_CALL ScNamedRangeObj::setPropertyValue(
     SolarMutexGuard aGuard;
     if ( rPropertyName == SC_UNONAME_ISSHAREDFMLA )
     {
-        bool bIsShared = false;
-        if( aValue >>= bIsShared )
-        {
-            sal_uInt16 nNewType = bIsShared ? RT_SHARED : RT_NAME;
-            Modify_Impl( NULL, NULL, NULL, NULL, &nNewType,formula::FormulaGrammar::GRAM_PODF_A1 );
-        }
+        // Ignore this.
     }
 }
 
@@ -417,8 +412,8 @@ uno::Any SAL_CALL ScNamedRangeObj::getPropertyValue( const OUString& rPropertyNa
     }
     else if ( rPropertyName == SC_UNONAME_ISSHAREDFMLA )
     {
-        if( ScRangeData* pData = GetRangeData_Impl() )
-            aRet <<= static_cast< bool >( pData->HasType( RT_SHARED ) );
+        if (GetRangeData_Impl())
+            aRet <<= false;
     }
     return aRet;
 }
commit c3f631ea5c09072a2e6bbb1f3a71b3a331b62713
Author: Kohei Yoshida <kohei.yoshida at gmail.com>
Date:   Wed Aug 7 18:46:57 2013 -0400

    Rework shared formula import in orcus handler.
    
    Change-Id: I3a6ed347565fff7cc984960929c66997e3a18f1e

diff --git a/sc/Library_scfilt.mk b/sc/Library_scfilt.mk
index 89b96ed..75ee0fe 100644
--- a/sc/Library_scfilt.mk
+++ b/sc/Library_scfilt.mk
@@ -133,6 +133,7 @@ $(eval $(call gb_Library_add_exception_objects,scfilt,\
 	sc/source/filter/ftools/fapihelper \
 	sc/source/filter/ftools/fprogressbar \
 	sc/source/filter/ftools/ftools \
+	sc/source/filter/ftools/sharedformulagroups \
 	sc/source/filter/html/htmlexp \
 	sc/source/filter/html/htmlexp2 \
 	sc/source/filter/html/htmlimp \
diff --git a/sc/source/filter/ftools/sharedformulagroups.cxx b/sc/source/filter/ftools/sharedformulagroups.cxx
new file mode 100644
index 0000000..77da587
--- /dev/null
+++ b/sc/source/filter/ftools/sharedformulagroups.cxx
@@ -0,0 +1,49 @@
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * This file is part of the LibreOffice project.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
+ */
+
+#include "sharedformulagroups.hxx"
+
+namespace sc {
+
+SharedFormulaGroups::Key::Key(size_t nId, SCCOL nCol) : mnId(nId), mnCol(nCol) {}
+
+bool SharedFormulaGroups::Key::operator== ( const Key& rOther ) const
+{
+    return mnId == rOther.mnId && mnCol == rOther.mnCol;
+}
+
+bool SharedFormulaGroups::Key::operator!= ( const Key& rOther ) const
+{
+    return !operator==(rOther);
+}
+
+size_t SharedFormulaGroups::KeyHash::operator ()( const Key& rKey ) const
+{
+    double nVal = rKey.mnId;
+    nVal *= 256.0;
+    nVal += rKey.mnCol;
+    return static_cast<size_t>(nVal);
+}
+
+void SharedFormulaGroups::set( size_t nSharedId, SCCOL nCol, const ScFormulaCellGroupRef& xGroup )
+{
+    Key aKey(nSharedId, nCol);
+    maStore.insert(StoreType::value_type(aKey, xGroup));
+}
+
+ScFormulaCellGroupRef SharedFormulaGroups::get( size_t nSharedId, SCCOL nCol ) const
+{
+    Key aKey(nSharedId, nCol);
+    StoreType::const_iterator it = maStore.find(aKey);
+    return it == maStore.end() ? ScFormulaCellGroupRef() : it->second;
+}
+
+}
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/sc/source/filter/inc/orcusinterface.hxx b/sc/source/filter/inc/orcusinterface.hxx
index 6e6f2db..75b49f4 100644
--- a/sc/source/filter/inc/orcusinterface.hxx
+++ b/sc/source/filter/inc/orcusinterface.hxx
@@ -12,6 +12,9 @@
 
 #include "address.hxx"
 #include "documentimport.hxx"
+
+#include "sharedformulagroups.hxx"
+
 #include "rtl/strbuf.hxx"
 
 #define __ORCUS_STATIC_LIB
@@ -68,6 +71,7 @@ class ScOrcusSheet : public orcus::spreadsheet::iface::import_sheet
     ScDocumentImport& mrDoc;
     SCTAB mnTab;
     ScOrcusFactory& mrFactory;
+    sc::SharedFormulaGroups maFormulaGroups;
 
     typedef std::map<size_t, ScRangeData*> SharedFormulaContainer;
     SharedFormulaContainer maSharedFormulas;
diff --git a/sc/source/filter/inc/sharedformulagroups.hxx b/sc/source/filter/inc/sharedformulagroups.hxx
new file mode 100644
index 0000000..c6058fc
--- /dev/null
+++ b/sc/source/filter/inc/sharedformulagroups.hxx
@@ -0,0 +1,50 @@
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * This file is part of the LibreOffice project.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
+ */
+
+#ifndef SC_FILTER_SHAREDFORMULAGROUPS_HXX
+#define SC_FILTER_SHAREDFORMULAGROUPS_HXX
+
+#include "address.hxx"
+#include "formulacell.hxx"
+
+#include <boost/unordered_map.hpp>
+
+namespace sc {
+
+class SharedFormulaGroups
+{
+    struct Key
+    {
+        size_t mnId;
+        SCCOL mnCol;
+
+        Key(size_t nId, SCCOL nCol);
+
+        bool operator== ( const Key& rOther ) const;
+        bool operator!= ( const Key& rOther ) const;
+    };
+
+    struct KeyHash
+    {
+        size_t operator() ( const Key& rKey ) const;
+    };
+
+    typedef boost::unordered_map<Key, ScFormulaCellGroupRef, KeyHash> StoreType;
+    StoreType maStore;
+public:
+
+    void set( size_t nSharedId, SCCOL nCol, const ScFormulaCellGroupRef& xGroup );
+    ScFormulaCellGroupRef get( size_t nSharedId, SCCOL nCol ) const;
+};
+
+}
+
+#endif
+
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/sc/source/filter/oox/formulabuffer.cxx b/sc/source/filter/oox/formulabuffer.cxx
index 66d15ea..59518bc 100644
--- a/sc/source/filter/oox/formulabuffer.cxx
+++ b/sc/source/filter/oox/formulabuffer.cxx
@@ -22,6 +22,7 @@
 #include "autonamecache.hxx"
 #include "tokenuno.hxx"
 #include "tokenarray.hxx"
+#include "sharedformulagroups.hxx"
 #include "oox/token/tokens.hxx"
 
 using namespace com::sun::star;
@@ -137,59 +138,6 @@ void FormulaBuffer::applyCellFormulaValues( const std::vector< ValueAddressPair
     }
 }
 
-namespace {
-
-class SharedFormulaGroups
-{
-    struct Key
-    {
-        sal_Int32 mnId;
-        sal_Int32 mnCol;
-
-        Key(sal_Int32 nId, sal_Int32 nCol) : mnId(nId), mnCol(nCol) {}
-
-        bool operator== ( const Key& rOther ) const
-        {
-            return mnId == rOther.mnId && mnCol == rOther.mnCol;
-        }
-
-        bool operator!= ( const Key& rOther ) const
-        {
-            return !operator==(rOther);
-        }
-    };
-
-    struct KeyHash
-    {
-        size_t operator() ( const Key& rKey ) const
-        {
-            double nVal = rKey.mnId;
-            nVal *= 256.0;
-            nVal += rKey.mnCol;
-            return static_cast<size_t>(nVal);
-        }
-    };
-
-    typedef boost::unordered_map<Key, ScFormulaCellGroupRef, KeyHash> StoreType;
-    StoreType maStore;
-public:
-
-    void set( sal_Int32 nSharedId, sal_Int32 nCol, const ScFormulaCellGroupRef& xGroup )
-    {
-        Key aKey(nSharedId, nCol);
-        maStore.insert(StoreType::value_type(aKey, xGroup));
-    }
-
-    ScFormulaCellGroupRef get( sal_Int32 nSharedId, sal_Int32 nCol ) const
-    {
-        Key aKey(nSharedId, nCol);
-        StoreType::const_iterator it = maStore.find(aKey);
-        return it == maStore.end() ? ScFormulaCellGroupRef() : it->second;
-    }
-};
-
-}
-
 void FormulaBuffer::applySharedFormulas( sal_Int32 nTab )
 {
     SheetToFormulaEntryMap::const_iterator itShared = sharedFormulas.find(nTab);
@@ -207,7 +155,7 @@ void FormulaBuffer::applySharedFormulas( sal_Int32 nTab )
 
     ScDocument& rDoc = getScDocument();
 
-    SharedFormulaGroups aGroups;
+    sc::SharedFormulaGroups aGroups;
     {
         // Process shared formulas first.
         std::vector<SharedFormulaEntry>::const_iterator it = rSharedFormulas.begin(), itEnd = rSharedFormulas.end();
@@ -231,7 +179,7 @@ void FormulaBuffer::applySharedFormulas( sal_Int32 nTab )
                     // shared formulas across multiple columns.
                     ScFormulaCellGroupRef xNewGroup(new ScFormulaCellGroup);
                     xNewGroup->mnStart = rRange.StartRow;
-                    xNewGroup->mnLength = rRange.EndRow - rRange.StartRow;
+                    xNewGroup->mnLength = rRange.EndRow - rRange.StartRow + 1;
                     xNewGroup->setCode(*pArray);
                     aGroups.set(nId, nCol, xNewGroup);
                 }
diff --git a/sc/source/filter/orcus/interface.cxx b/sc/source/filter/orcus/interface.cxx
index a3c1e6d..495715f 100644
--- a/sc/source/filter/orcus/interface.cxx
+++ b/sc/source/filter/orcus/interface.cxx
@@ -16,6 +16,7 @@
 #include "globalnames.hxx"
 #include "docoptio.hxx"
 #include "globstr.hrc"
+#include "compiler.hxx"
 
 #include "formula/token.hxx"
 #include "tools/datetime.hxx"
@@ -256,7 +257,7 @@ formula::FormulaGrammar::Grammar getCalcGrammarFromOrcus( os::formula_grammar_t
             break;
         case orcus::spreadsheet::xlsx_2007:
         case orcus::spreadsheet::xlsx_2010:
-            eGrammar = formula::FormulaGrammar::GRAM_ENGLISH_XL_A1;
+            eGrammar = formula::FormulaGrammar::GRAM_ENGLISH_XL_OOX;
             break;
         case orcus::spreadsheet::gnumeric:
             eGrammar = formula::FormulaGrammar::GRAM_ENGLISH_XL_A1;
@@ -266,6 +267,55 @@ formula::FormulaGrammar::Grammar getCalcGrammarFromOrcus( os::formula_grammar_t
     return eGrammar;
 }
 
+class SharedFormulaGroups
+{
+    struct Key
+    {
+        sal_Int32 mnId;
+        sal_Int32 mnCol;
+
+        Key(sal_Int32 nId, sal_Int32 nCol) : mnId(nId), mnCol(nCol) {}
+
+        bool operator== ( const Key& rOther ) const
+        {
+            return mnId == rOther.mnId && mnCol == rOther.mnCol;
+        }
+
+        bool operator!= ( const Key& rOther ) const
+        {
+            return !operator==(rOther);
+        }
+    };
+
+    struct KeyHash
+    {
+        size_t operator() ( const Key& rKey ) const
+        {
+            double nVal = rKey.mnId;
+            nVal *= 256.0;
+            nVal += rKey.mnCol;
+            return static_cast<size_t>(nVal);
+        }
+    };
+
+    typedef boost::unordered_map<Key, ScFormulaCellGroupRef, KeyHash> StoreType;
+    StoreType maStore;
+public:
+
+    void set( sal_Int32 nSharedId, sal_Int32 nCol, const ScFormulaCellGroupRef& xGroup )
+    {
+        Key aKey(nSharedId, nCol);
+        maStore.insert(StoreType::value_type(aKey, xGroup));
+    }
+
+    ScFormulaCellGroupRef get( sal_Int32 nSharedId, sal_Int32 nCol ) const
+    {
+        Key aKey(nSharedId, nCol);
+        StoreType::const_iterator it = maStore.find(aKey);
+        return it == maStore.end() ? ScFormulaCellGroupRef() : it->second;
+    }
+};
+
 }
 
 void ScOrcusSheet::set_formula(
@@ -291,57 +341,76 @@ void ScOrcusSheet::set_formula_result(os::row_t row, os::col_t col, const char*
 }
 
 void ScOrcusSheet::set_shared_formula(
-    os::row_t row, os::col_t col, os::formula_grammar_t grammar, size_t sindex,
-    const char* p_formula, size_t n_formula)
+    os::row_t /*row*/, os::col_t /*col*/, os::formula_grammar_t /*grammar*/, size_t /*sindex*/,
+    const char* /*p_formula*/, size_t /*n_formula*/)
 {
-    OUString aFormula( p_formula, n_formula, RTL_TEXTENCODING_UTF8 );
-    formula::FormulaGrammar::Grammar eGrammar =  getCalcGrammarFromOrcus( grammar );
-    ScRangeName* pRangeName = mrDoc.getDoc().GetRangeName();
-
-    OUString aName("shared_");
-    aName += OUString::valueOf(sal_Int32(pRangeName->size()));
-    ScRangeData* pSharedFormula = new ScRangeData(&mrDoc.getDoc(), aName, aFormula, ScAddress(col, row, mnTab), RT_SHARED, eGrammar);
-    if(pRangeName->insert(pSharedFormula))
-    {
-        maSharedFormulas.insert( std::pair<size_t, ScRangeData*>(sindex, pSharedFormula) );
-        ScTokenArray aArr;
-        aArr.AddToken( formula::FormulaIndexToken( ocName, pSharedFormula->GetIndex() ) );
-        mrDoc.setFormulaCell(ScAddress(col,row,mnTab), aArr);
-        cellInserted();
-    }
+    // TODO: We need to revise this interface in orcus.
 }
 
 void ScOrcusSheet::set_shared_formula(
     os::row_t row, os::col_t col, os::formula_grammar_t grammar, size_t sindex,
-    const char* p_formula, size_t n_formula, const char* /*p_range*/, size_t /*n_range*/)
-{
-    OUString aFormula( p_formula, n_formula, RTL_TEXTENCODING_UTF8 );
-    formula::FormulaGrammar::Grammar eGrammar = getCalcGrammarFromOrcus( grammar );
-    ScRangeName* pRangeName = mrDoc.getDoc().GetRangeName();
+    const char* p_formula, size_t n_formula, const char* p_range, size_t n_range)
+{
+    ScAddress aPos(col, row, mnTab);
+    OUString aFormula(p_formula, n_formula, RTL_TEXTENCODING_UTF8);
+    OUString aRangeStr(p_range, n_range, RTL_TEXTENCODING_UTF8);
+    formula::FormulaGrammar::Grammar eGram = getCalcGrammarFromOrcus(grammar);
+    formula::FormulaGrammar::AddressConvention eConv = formula::FormulaGrammar::extractRefConvention(eGram);
+
+    // Convert the shared formula range.
+    ScRange aRange;
+    sal_uInt16 nRes = aRange.Parse(aRangeStr, &mrDoc.getDoc(), eConv);
+    if (!(nRes & SCA_VALID))
+        // Conversion failed.
+        return;
+
+    // Compile the formula expression into tokens.
+    ScCompiler aComp(&mrDoc.getDoc(), aPos);
+    aComp.SetGrammar(eGram);
+    ScTokenArray* pArray = aComp.CompileString(aFormula);
+    if (!pArray)
+        // Tokenization failed.
+        return;
 
-    OUString aName("shared_");
-    aName += OUString::valueOf(sal_Int32(pRangeName->size()));
-    ScRangeData* pSharedFormula = new ScRangeData(&mrDoc.getDoc(), aName, aFormula, ScAddress(col, row, mnTab), RT_SHARED, eGrammar);
-    if(pRangeName->insert(pSharedFormula))
+    for (sal_Int32 nCol = aRange.aStart.Col(); nCol <= aRange.aEnd.Col(); ++nCol)
     {
-        maSharedFormulas.insert( std::pair<size_t, ScRangeData*>(sindex, pSharedFormula) );
-        ScTokenArray aArr;
-        aArr.AddToken( formula::FormulaIndexToken( ocName, pSharedFormula->GetIndex() ) );
-        mrDoc.setFormulaCell(ScAddress(col,row,mnTab), aArr);
-        cellInserted();
+        // Create one group per column, since Calc doesn't support shared
+        // formulas across multiple columns.
+        ScFormulaCellGroupRef xNewGroup(new ScFormulaCellGroup);
+        xNewGroup->mnStart = aRange.aStart.Row();
+        xNewGroup->mnLength = aRange.aEnd.Row() - aRange.aStart.Row() + 1;
+        xNewGroup->setCode(*pArray);
+        maFormulaGroups.set(sindex, nCol, xNewGroup);
     }
+
+    ScFormulaCellGroupRef xGroup = maFormulaGroups.get(sindex, aPos.Col());
+    if (!xGroup)
+        return;
+
+    ScFormulaCell* pCell = new ScFormulaCell(&mrDoc.getDoc(), aPos, xGroup);
+    mrDoc.setFormulaCell(aPos, pCell);
+    cellInserted();
+
+    // For now, orcus doesn't support setting cached result. Mark it for re-calculation.
+    pCell->SetDirty(true);
+    pCell->StartListeningTo(&mrDoc.getDoc());
 }
 
 void ScOrcusSheet::set_shared_formula(os::row_t row, os::col_t col, size_t sindex)
 {
-    if(maSharedFormulas.find(sindex) == maSharedFormulas.end())
+    ScAddress aPos(col, row, mnTab);
+
+    ScFormulaCellGroupRef xGroup = maFormulaGroups.get(sindex, aPos.Col());
+    if (!xGroup)
         return;
 
-    ScRangeData* pSharedFormula = maSharedFormulas.find(sindex)->second;
-    ScTokenArray aArr;
-    aArr.AddToken( formula::FormulaIndexToken( ocName, pSharedFormula->GetIndex() ) );
-    mrDoc.setFormulaCell(ScAddress(col,row,mnTab), aArr);
+    ScFormulaCell* pCell = new ScFormulaCell(&mrDoc.getDoc(), aPos, xGroup);
+    mrDoc.setFormulaCell(aPos, pCell);
     cellInserted();
+
+    // For now, orcus doesn't support setting cached result. Mark it for re-calculation.
+    pCell->SetDirty(true);
+    pCell->StartListeningTo(&mrDoc.getDoc());
 }
 
 void ScOrcusSheet::set_array_formula(
commit 3c4fb3d0741a762fd21cc4e0dad631a81f1057f3
Author: Kohei Yoshida <kohei.yoshida at gmail.com>
Date:   Wed Aug 7 17:30:20 2013 -0400

    This code is no longer needed.
    
    Change-Id: I319aae9d58fe1798e6add168f5a3613bceef7c26

diff --git a/sc/source/filter/inc/sheetdatabuffer.hxx b/sc/source/filter/inc/sheetdatabuffer.hxx
index 563145e..e826bd2 100644
--- a/sc/source/filter/inc/sheetdatabuffer.hxx
+++ b/sc/source/filter/inc/sheetdatabuffer.hxx
@@ -143,12 +143,6 @@ public:
                             const ::com::sun::star::table::CellRangeAddress& rRange,
                             const DataTableModel& rModel );
 
-    /** Creates a named range with a special name for a shared formula with the
-        specified base address and formula definition (BIFF only). */
-    void                createSharedFormula(
-                            const ::com::sun::star::table::CellAddress& rCellAddr,
-                            const ApiTokenSequence& rTokens );
-
     /** Sets default cell formatting for the specified range of rows. */
     void                setRowFormat( sal_Int32 nRow, sal_Int32 nXfId, bool bCustomFormat );
     /** Merges the cells in the passed cell range. */
@@ -173,9 +167,6 @@ private:
                             const ::com::sun::star::table::CellAddress& rCellAddr,
                             const ApiTokenSequence& rTokens );
 
-    /** Creates a named range with a special name for a shared formula with the
-        specified base address and formula definition. */
-    void                createSharedFormula( const BinAddress& rMapKey, const ApiTokenSequence& rTokens );
     /** Creates a formula token array representing the shared formula with the
         passed identifier. */
     ApiTokenSequence    resolveSharedFormula( const BinAddress& rMapKey ) const;
diff --git a/sc/source/filter/oox/sheetdatabuffer.cxx b/sc/source/filter/oox/sheetdatabuffer.cxx
index 174842a..99e8054 100644
--- a/sc/source/filter/oox/sheetdatabuffer.cxx
+++ b/sc/source/filter/oox/sheetdatabuffer.cxx
@@ -276,11 +276,6 @@ void SheetDataBuffer::createTableOperation( const CellRangeAddress& rRange, cons
     maTableOperations.push_back( TableOperation( rRange, rModel ) );
 }
 
-void SheetDataBuffer::createSharedFormula( const CellAddress& rCellAddr, const ApiTokenSequence& rTokens )
-{
-    createSharedFormula( BinAddress( rCellAddr ), rTokens );
-}
-
 void SheetDataBuffer::setRowFormat( sal_Int32 nRow, sal_Int32 nXfId, bool bCustomFormat )
 {
     // set row formatting
@@ -554,33 +549,6 @@ void SheetDataBuffer::setCellFormula( const CellAddress& rCellAddr, const ApiTok
     }
 }
 
-void SheetDataBuffer::createSharedFormula( const BinAddress& rMapKey, const ApiTokenSequence& rTokens )
-{
-    // create the defined name that will represent the shared formula
-    OUString aName = OUStringBuffer().appendAscii( RTL_CONSTASCII_STRINGPARAM( "__shared_" ) ).
-        append( static_cast< sal_Int32 >( getSheetIndex() + 1 ) ).
-        append( sal_Unicode( '_' ) ).append( rMapKey.mnRow ).
-        append( sal_Unicode( '_' ) ).append( rMapKey.mnCol ).makeStringAndClear();
-    ScRangeData* pScRangeData = createNamedRangeObject( aName, rTokens, 0 );
-    pScRangeData->SetType(RT_SHARED);
-
-    // get and store the token index of the defined name
-    OSL_ENSURE( maSharedFormulas.count( rMapKey ) == 0, "SheetDataBuffer::createSharedFormula - shared formula exists already" );
-    sal_Int32 nTokenIndex = static_cast< sal_Int32 >( pScRangeData->GetIndex() );
-    if( nTokenIndex >= 0 ) try
-    {
-        // store the token index in the map
-        maSharedFormulas[ rMapKey ] = nTokenIndex;
-        // retry to insert a pending shared formula cell
-        if( mbPendingSharedFmla )
-            setCellFormula( maSharedFmlaAddr, resolveSharedFormula( maSharedBaseAddr ) );
-    }
-    catch( Exception& )
-    {
-    }
-    mbPendingSharedFmla = false;
-}
-
 ApiTokenSequence SheetDataBuffer::resolveSharedFormula( const BinAddress& rMapKey ) const
 {
     sal_Int32 nTokenIndex = ContainerHelper::getMapElement( maSharedFormulas, rMapKey, -1 );
diff --git a/sc/source/filter/oox/sheetdatacontext.cxx b/sc/source/filter/oox/sheetdatacontext.cxx
index 24be4d7..3aaaaac 100644
--- a/sc/source/filter/oox/sheetdatacontext.cxx
+++ b/sc/source/filter/oox/sheetdatacontext.cxx
@@ -578,17 +578,10 @@ void SheetDataContext::importDataTable( SequenceInputStream& rStrm )
     }
 }
 
-void SheetDataContext::importSharedFmla( SequenceInputStream& rStrm )
+void SheetDataContext::importSharedFmla( SequenceInputStream& /*rStrm*/ )
 {
-    if( readFormulaRef( rStrm ) && maFmlaData.isValidSharedRef( maCellData.maCellAddr ) )
-    {
-        ApiTokenSequence aTokens = mrFormulaParser.importFormula( maCellData.maCellAddr, FORMULATYPE_SHAREDFORMULA, rStrm );
-        mrSheetData.createSharedFormula( maCellData.maCellAddr, aTokens );
-    }
 }
 
-// ============================================================================
-
 } // namespace xls
 } // namespace oox
 
commit e1c2403802af2f13075d612ea5ef0e91cf23c878
Author: Kohei Yoshida <kohei.yoshida at gmail.com>
Date:   Wed Aug 7 16:35:06 2013 -0400

    Map shared formulas to Calc's formula groups on xlsx import.
    
    Change-Id: If8d11c5ee55afd8529070a699ca50284880ceb45

diff --git a/sc/source/filter/excel/namebuff.cxx b/sc/source/filter/excel/namebuff.cxx
index ac609a4..4e47c09 100644
--- a/sc/source/filter/excel/namebuff.cxx
+++ b/sc/source/filter/excel/namebuff.cxx
@@ -89,8 +89,6 @@ void SharedFormulaBuffer::Store( const ScRange& rRange, const ScTokenArray& rArr
         ScFormulaCellGroupRef xNewGroup(new ScFormulaCellGroup);
         xNewGroup->mnStart = rRange.aStart.Row();
         xNewGroup->mnLength = nGroupLen;
-        xNewGroup->mpCode = rArray.Clone();
-        xNewGroup->mbInvariant = rArray.IsInvariant();
         xNewGroup->setCode(rArray);
         maFormulaGroups.insert(FormulaGroupsType::value_type(aPos, xNewGroup));
     }
diff --git a/sc/source/filter/inc/formulabuffer.hxx b/sc/source/filter/inc/formulabuffer.hxx
index 1e98060..c5d8f96 100644
--- a/sc/source/filter/inc/formulabuffer.hxx
+++ b/sc/source/filter/inc/formulabuffer.hxx
@@ -29,13 +29,35 @@ namespace oox { namespace xls {
 
 class FormulaBuffer : public WorkbookHelper
 {
+    /**
+     * Represents a shared formula definition.
+     */
     struct SharedFormulaEntry
     {
-        ::com::sun::star::table::CellAddress maAddress;
+        com::sun::star::table::CellAddress maAddress;
+        com::sun::star::table::CellRangeAddress maRange;
         OUString maTokenStr;
         sal_Int32 mnSharedId;
-        ::com::sun::star::uno::Reference< ::com::sun::star::sheet::XFormulaTokens > mxFormulaTokens;
-        SharedFormulaEntry( const ::com::sun::star::table::CellAddress& rAddress, const OUString& rTokenStr, sal_Int32 nSharedId ) : maAddress( rAddress ), maTokenStr( rTokenStr ), mnSharedId( nSharedId ) {}
+
+        SharedFormulaEntry(
+            const com::sun::star::table::CellAddress& rAddress,
+            const com::sun::star::table::CellRangeAddress& rRange,
+            const OUString& rTokenStr, sal_Int32 nSharedId );
+    };
+
+    /**
+     * Represents a formula cell that uses shared formula.
+     */
+    struct SharedFormulaDesc
+    {
+        com::sun::star::table::CellAddress maAddress;
+        sal_Int32 mnSharedId;
+        OUString maCellValue;
+        sal_Int32 mnValueType;
+
+        SharedFormulaDesc(
+            const com::sun::star::table::CellAddress& rAddr, sal_Int32 nSharedId,
+            const OUString& rCellValue, sal_Int32 nValueType );
     };
 
     struct TokenAddressItem
@@ -54,8 +76,6 @@ class FormulaBuffer : public WorkbookHelper
 
     typedef ::std::map< sal_Int32, std::vector< TokenAddressItem > > FormulaDataMap;
     typedef ::std::map< sal_Int32, std::vector< TokenRangeAddressItem > > ArrayFormulaDataMap;
-    // shared formuala descriptions, the id and address the formula is at
-    typedef std::pair< ::com::sun::star::table::CellAddress, sal_Int32 > SharedFormulaDesc;
     // sheet -> list of shared formula descriptions
     typedef ::std::map< sal_Int32, std::vector< SharedFormulaDesc > > SheetToSharedFormulaid;
     // sheet -> stuff needed to create shared formulae
@@ -66,7 +86,6 @@ class FormulaBuffer : public WorkbookHelper
     typedef ::std::pair< ::com::sun::star::table::CellAddress, double > ValueAddressPair;
     typedef ::std::map< sal_Int32, std::vector< ValueAddressPair > > FormulaValueMap;
 
-    void createSharedFormula(  const ::com::sun::star::table::CellAddress& rAddress,  sal_Int32 nSharedId, const OUString& rTokens );
     ::com::sun::star::uno::Reference< com::sun::star::table::XCellRange > getRange( const ::com::sun::star::table::CellRangeAddress& rRange);
     com::sun::star::uno::Reference< com::sun::star::sheet::XSpreadsheet > mxCurrSheet;
     FormulaDataMap      cellFormulas;
@@ -80,15 +99,23 @@ class FormulaBuffer : public WorkbookHelper
     void                applyCellFormula( ScDocument& rDoc, const ApiTokenSequence& rTokens, const ::com::sun::star::table::CellAddress& rAddress );
     void                applyCellFormulas(  const std::vector< TokenAddressItem >& rVector );
     void                applyCellFormulaValues( const std::vector< ValueAddressPair >& rVector );
+    void applySharedFormulas( sal_Int32 nTab );
 
 public:
     explicit            FormulaBuffer( const WorkbookHelper& rHelper );
     void                finalizeImport();
     void                setCellFormula( const ::com::sun::star::table::CellAddress& rAddress, const OUString&  );
-    void                setCellFormula( const ::com::sun::star::table::CellAddress& rAddress, sal_Int32 nSharedId );
+
+    void setCellFormula(
+        const ::com::sun::star::table::CellAddress& rAddress, sal_Int32 nSharedId,
+        const OUString& rCellValue, sal_Int32 nValueType );
+
     void                setCellFormulaValue( const ::com::sun::star::table::CellAddress& rAddress, double fValue  );
     void                setCellArrayFormula( const ::com::sun::star::table::CellRangeAddress& rRangeAddress, const ::com::sun::star::table::CellAddress& rTokenAddress, const OUString&  );
-    void                createSharedFormulaMapEntry( const ::com::sun::star::table::CellAddress& rAddress, sal_Int32 nSharedId, const OUString& rTokens );
+    void createSharedFormulaMapEntry(
+        const com::sun::star::table::CellAddress& rAddress,
+        const com::sun::star::table::CellRangeAddress& rRange,
+        sal_Int32 nSharedId, const OUString& rTokens );
 };
 
 }}
diff --git a/sc/source/filter/inc/workbookhelper.hxx b/sc/source/filter/inc/workbookhelper.hxx
index f4ce1cc..e540ba0 100644
--- a/sc/source/filter/inc/workbookhelper.hxx
+++ b/sc/source/filter/inc/workbookhelper.hxx
@@ -156,7 +156,7 @@ public:
 
     /** Returns a reference to the specified spreadsheet in the document model. */
     ::com::sun::star::uno::Reference< ::com::sun::star::sheet::XSpreadsheet >
-                        getSheetFromDoc( sal_Int16 nSheet ) const;
+                        getSheetFromDoc( sal_Int32 nSheet ) const;
     /** Returns a reference to the specified spreadsheet in the document model. */
     ::com::sun::star::uno::Reference< ::com::sun::star::sheet::XSpreadsheet >
                         getSheetFromDoc( const OUString& rSheet ) const;
diff --git a/sc/source/filter/inc/worksheethelper.hxx b/sc/source/filter/inc/worksheethelper.hxx
index 53b7ed1..270cafe 100644
--- a/sc/source/filter/inc/worksheethelper.hxx
+++ b/sc/source/filter/inc/worksheethelper.hxx
@@ -307,9 +307,18 @@ public:
     void finalizeDrawingImport();
 
     void                setCellFormula( const ::com::sun::star::table::CellAddress& rTokenAddress, const OUString&  );
-    void                setCellFormula( const ::com::sun::star::table::CellAddress& rTokenAddress, sal_Int32  );
+
+    void setCellFormula(
+        const com::sun::star::table::CellAddress& rAddr, sal_Int32 nSharedId,
+        const OUString& rCellValue, sal_Int32 nValueType );
+
     void                setCellArrayFormula( const ::com::sun::star::table::CellRangeAddress& rRangeAddress, const ::com::sun::star::table::CellAddress& rTokenAddress, const OUString&  );
-    void                createSharedFormulaMapEntry( const ::com::sun::star::table::CellAddress& rAddress, sal_Int32 nSharedId, const OUString& rTokens );
+
+    void createSharedFormulaMapEntry(
+        const com::sun::star::table::CellAddress& rAddress,
+        const com::sun::star::table::CellRangeAddress& rRange,
+        sal_Int32 nSharedId, const OUString& rTokens );
+
     void                setCellFormulaValue( const ::com::sun::star::table::CellAddress& rAddress,
                             double fValue  );
 private:
diff --git a/sc/source/filter/oox/formulabuffer.cxx b/sc/source/filter/oox/formulabuffer.cxx
index 3889b53..66d15ea 100644
--- a/sc/source/filter/oox/formulabuffer.cxx
+++ b/sc/source/filter/oox/formulabuffer.cxx
@@ -22,15 +22,26 @@
 #include "autonamecache.hxx"
 #include "tokenuno.hxx"
 #include "tokenarray.hxx"
+#include "oox/token/tokens.hxx"
 
-namespace oox {
-namespace xls {
-
+using namespace com::sun::star;
 using namespace ::com::sun::star::uno;
 using namespace ::com::sun::star::table;
 using namespace ::com::sun::star::sheet;
 using namespace ::com::sun::star::container;
 
+namespace oox { namespace xls {
+
+FormulaBuffer::FormulaBuffer::SharedFormulaEntry::SharedFormulaEntry(
+    const table::CellAddress& rAddr, const table::CellRangeAddress& rRange,
+    const OUString& rTokenStr, sal_Int32 nSharedId ) :
+    maAddress(rAddr), maRange(rRange), maTokenStr(rTokenStr), mnSharedId(nSharedId) {}
+
+FormulaBuffer::FormulaBuffer::SharedFormulaDesc::SharedFormulaDesc(
+    const com::sun::star::table::CellAddress& rAddr, sal_Int32 nSharedId,
+    const OUString& rCellValue, sal_Int32 nValueType ) :
+    maAddress(rAddr), mnSharedId(nSharedId), maCellValue(rCellValue), mnValueType(nValueType) {}
+
 FormulaBuffer::FormulaBuffer( const WorkbookHelper& rHelper ) : WorkbookHelper( rHelper )
 {
 }
@@ -55,43 +66,13 @@ void FormulaBuffer::finalizeImport()
     ScDocument& rDoc = getScDocument();
     Reference< XIndexAccess > xSheets( getDocument()->getSheets(), UNO_QUERY_THROW );
     rDoc.SetAutoNameCache( new ScAutoNameCache( &rDoc ) );
-    for ( sal_Int16 nTab = 0, nElem = xSheets->getCount(); nTab < nElem; ++nTab )
+    for ( sal_Int32 nTab = 0, nElem = xSheets->getCount(); nTab < nElem; ++nTab )
     {
         double fPosition = static_cast< double> (nTab + 1) /static_cast<double>(nElem);
         xFormulaBar->setPosition( fPosition );
         mxCurrSheet = getSheetFromDoc( nTab );
-        // process shared Formula
-        SheetToFormulaEntryMap::iterator sharedIt = sharedFormulas.find( nTab );
-        if ( sharedIt != sharedFormulas.end() )
-        {
-            // shared id ( to create the special shared names from )
-            std::vector<SharedFormulaEntry>& rSharedFormulas = sharedIt->second;
-            for ( std::vector<SharedFormulaEntry>::iterator it = rSharedFormulas.begin(), it_end = rSharedFormulas.end(); it != it_end; ++it )
-            {
-                 createSharedFormula( it->maAddress, it->mnSharedId, it->maTokenStr );
-            }
-        }
-        // now process any defined shared formulae
-        SheetToSharedFormulaid::iterator formulDescIt = sharedFormulaIds.find( nTab );
-        SheetToSharedIdToTokenIndex::iterator tokensIt = tokenIndexes.find( nTab );
-        if ( formulDescIt != sharedFormulaIds.end() && tokensIt !=  tokenIndexes.end() )
-        {
-            SharedIdToTokenIndex& rTokenIdMap = tokensIt->second;
-            std::vector< SharedFormulaDesc >& rVector = formulDescIt->second;
-            for ( std::vector< SharedFormulaDesc >::iterator it = rVector.begin(), it_end = rVector.end(); it != it_end; ++it )
-            {
-                // see if we have a
-                // resolved tokenId
-                CellAddress& rAddress = it->first;
-                sal_Int32& rnSharedId = it->second;
-                SharedIdToTokenIndex::iterator itTokenId =  rTokenIdMap.find( rnSharedId );
-                if ( itTokenId != rTokenIdMap.end() )
-                {
-                    ApiTokenSequence aTokens =  getFormulaParser().convertNameToFormula( itTokenId->second );
-                    applyCellFormula( rDoc, aTokens, rAddress );
-                }
-            }
-        }
+
+        applySharedFormulas(nTab);
 
         FormulaDataMap::iterator cellIt = cellFormulas.find( nTab );
         if ( cellIt != cellFormulas.end() )
@@ -155,6 +136,157 @@ void FormulaBuffer::applyCellFormulaValues( const std::vector< ValueAddressPair
         }
     }
 }
+
+namespace {
+
+class SharedFormulaGroups
+{
+    struct Key
+    {
+        sal_Int32 mnId;
+        sal_Int32 mnCol;
+
+        Key(sal_Int32 nId, sal_Int32 nCol) : mnId(nId), mnCol(nCol) {}
+
+        bool operator== ( const Key& rOther ) const
+        {
+            return mnId == rOther.mnId && mnCol == rOther.mnCol;
+        }
+
+        bool operator!= ( const Key& rOther ) const
+        {
+            return !operator==(rOther);
+        }
+    };
+
+    struct KeyHash
+    {
+        size_t operator() ( const Key& rKey ) const
+        {
+            double nVal = rKey.mnId;
+            nVal *= 256.0;
+            nVal += rKey.mnCol;
+            return static_cast<size_t>(nVal);
+        }
+    };
+
+    typedef boost::unordered_map<Key, ScFormulaCellGroupRef, KeyHash> StoreType;
+    StoreType maStore;
+public:
+
+    void set( sal_Int32 nSharedId, sal_Int32 nCol, const ScFormulaCellGroupRef& xGroup )
+    {
+        Key aKey(nSharedId, nCol);
+        maStore.insert(StoreType::value_type(aKey, xGroup));
+    }
+
+    ScFormulaCellGroupRef get( sal_Int32 nSharedId, sal_Int32 nCol ) const
+    {
+        Key aKey(nSharedId, nCol);
+        StoreType::const_iterator it = maStore.find(aKey);
+        return it == maStore.end() ? ScFormulaCellGroupRef() : it->second;
+    }
+};
+
+}
+
+void FormulaBuffer::applySharedFormulas( sal_Int32 nTab )
+{
+    SheetToFormulaEntryMap::const_iterator itShared = sharedFormulas.find(nTab);
+    if (itShared == sharedFormulas.end())
+        // There is no shared formulas for this sheet.
+        return;
+
+    SheetToSharedFormulaid::const_iterator itCells = sharedFormulaIds.find(nTab);
+    if (itCells == sharedFormulaIds.end())
+        // There is no formula cells that use shared formulas for this sheet.
+        return;
+
+    const std::vector<SharedFormulaEntry>& rSharedFormulas = itShared->second;
+    const std::vector<SharedFormulaDesc>& rCells = itCells->second;
+
+    ScDocument& rDoc = getScDocument();
+
+    SharedFormulaGroups aGroups;
+    {
+        // Process shared formulas first.
+        std::vector<SharedFormulaEntry>::const_iterator it = rSharedFormulas.begin(), itEnd = rSharedFormulas.end();
+        for (; it != itEnd; ++it)
+        {
+            const table::CellAddress& rAddr = it->maAddress;
+            const table::CellRangeAddress& rRange = it->maRange;
+            sal_Int32 nId = it->mnSharedId;
+            const OUString& rTokenStr = it->maTokenStr;
+
+            ScAddress aPos;
+            ScUnoConversion::FillScAddress(aPos, rAddr);
+            ScCompiler aComp(&rDoc, aPos);
+            aComp.SetGrammar(formula::FormulaGrammar::GRAM_ENGLISH_XL_OOX);
+            ScTokenArray* pArray = aComp.CompileString(rTokenStr);
+            if (pArray)
+            {
+                for (sal_Int32 nCol = rRange.StartColumn; nCol <= rRange.EndColumn; ++nCol)
+                {
+                    // Create one group per column, since Calc doesn't support
+                    // shared formulas across multiple columns.
+                    ScFormulaCellGroupRef xNewGroup(new ScFormulaCellGroup);
+                    xNewGroup->mnStart = rRange.StartRow;
+                    xNewGroup->mnLength = rRange.EndRow - rRange.StartRow;
+                    xNewGroup->setCode(*pArray);
+                    aGroups.set(nId, nCol, xNewGroup);
+                }
+            }
+        }
+    }
+
+    {
+        // Process formulas that use shared formulas.
+        std::vector<SharedFormulaDesc>::const_iterator it = rCells.begin(), itEnd = rCells.end();
+        for (; it != itEnd; ++it)
+        {
+            const table::CellAddress& rAddr = it->maAddress;
+
+            ScFormulaCellGroupRef xGroup = aGroups.get(it->mnSharedId, rAddr.Column);
+            if (!xGroup)
+                continue;
+
+            ScAddress aPos;
+            ScUnoConversion::FillScAddress(aPos, rAddr);
+            ScFormulaCell* pCell = new ScFormulaCell(&rDoc, aPos, xGroup);
+
+            bool bInserted = rDoc.SetGroupFormulaCell(aPos, pCell);
+            if (!bInserted)
+            {
+                // Insertion failed.
+                delete pCell;
+                continue;
+            }
+
+            pCell->StartListeningTo(&rDoc);
+
+            if (it->maCellValue.isEmpty())
+            {
+                // No cached cell value. Mark it for re-calculation.
+                pCell->SetDirty(true);
+                continue;
+            }
+
+            // Set cached formula results. For now, we only use numeric
+            // results. Find out how to utilize cached results of other types.
+            switch (it->mnValueType)
+            {
+                case XML_n:
+                    // numeric value.
+                    pCell->SetResultDouble(it->maCellValue.toDouble());
+                break;
+                default:
+                    // Mark it for re-calculation.
+                    pCell->SetDirty(true);
+            }
+        }
+    }
+}
+
 // bound to need this somewhere else, if so probably need to move it to
 // worksheethelper or somewhere else more suitable
 void StartCellListening( sal_Int16 nSheet, sal_Int32 nRow, sal_Int32 nCol, ScDocument& rDoc )
@@ -193,10 +325,12 @@ void FormulaBuffer::applyArrayFormulas( const std::vector< TokenRangeAddressItem
     }
 }
 
-void FormulaBuffer::createSharedFormulaMapEntry( const ::com::sun::star::table::CellAddress& rAddress, sal_Int32 nSharedId, const OUString& rTokens )
+void FormulaBuffer::createSharedFormulaMapEntry(
+    const table::CellAddress& rAddress, const table::CellRangeAddress& rRange,
+    sal_Int32 nSharedId, const OUString& rTokens )
 {
     std::vector<SharedFormulaEntry>& rSharedFormulas = sharedFormulas[ rAddress.Sheet ];
-    SharedFormulaEntry aEntry( rAddress, rTokens, nSharedId );
+    SharedFormulaEntry aEntry(rAddress, rRange, rTokens, nSharedId);
     rSharedFormulas.push_back( aEntry );
 }
 
@@ -205,9 +339,11 @@ void FormulaBuffer::setCellFormula( const ::com::sun::star::table::CellAddress&
     cellFormulas[ rAddress.Sheet ].push_back( TokenAddressItem( rTokenStr, rAddress ) );
 }
 
-void FormulaBuffer::setCellFormula( const ::com::sun::star::table::CellAddress& rAddress, sal_Int32 nSharedId )
+void FormulaBuffer::setCellFormula(
+    const table::CellAddress& rAddress, sal_Int32 nSharedId, const OUString& rCellValue, sal_Int32 nValueType )
 {
-    sharedFormulaIds[ rAddress.Sheet ].push_back( SharedFormulaDesc( rAddress, nSharedId ) );
+    sharedFormulaIds[rAddress.Sheet].push_back(
+        SharedFormulaDesc(rAddress, nSharedId, rCellValue, nValueType));
 }
 
 void FormulaBuffer::setCellArrayFormula( const ::com::sun::star::table::CellRangeAddress& rRangeAddress, const ::com::sun::star::table::CellAddress& rTokenAddress, const OUString& rTokenStr )
@@ -222,21 +358,6 @@ void FormulaBuffer::setCellFormulaValue( const ::com::sun::star::table::CellAddr
     cellFormulaValues[ rAddress.Sheet ].push_back( ValueAddressPair( rAddress, fValue ) );
 }
 
-void FormulaBuffer::createSharedFormula( const ::com::sun::star::table::CellAddress& rAddress,  sal_Int32 nSharedId, const OUString& rTokenStr )
-{
-    ApiTokenSequence aTokens = getFormulaParser().importFormula( rAddress, rTokenStr );
-    OUString aName = OUStringBuffer().appendAscii( RTL_CONSTASCII_STRINGPARAM( "__shared_" ) ).
-        append( static_cast< sal_Int32 >( rAddress.Sheet + 1 ) ).
-        append( sal_Unicode( '_' ) ).append( nSharedId ).
-        append( OUString("_0") ).makeStringAndClear();
-    ScRangeData* pScRangeData  = createNamedRangeObject( aName, aTokens, 0  );
-
-    pScRangeData->SetType(RT_SHARED);
-    sal_Int32 nTokenIndex = static_cast< sal_Int32 >( pScRangeData->GetIndex() );
-
-        // store the token index in the map
-   tokenIndexes[  rAddress.Sheet ][ nSharedId ] = nTokenIndex;
-}
-} // namespace xls
-} // namespace oox
+}}
+
 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
diff --git a/sc/source/filter/oox/sheetdatacontext.cxx b/sc/source/filter/oox/sheetdatacontext.cxx
index e1efe16..24be4d7 100644
--- a/sc/source/filter/oox/sheetdatacontext.cxx
+++ b/sc/source/filter/oox/sheetdatacontext.cxx
@@ -157,7 +157,7 @@ void SheetDataContext::onCharacters( const OUString& rChars )
         case XLS_TOKEN( f ):
             if( maFmlaData.mnFormulaType != XML_TOKEN_INVALID )
             {
-                  maFormulaStr = rChars;
+                maFormulaStr = rChars;
             }
         break;
     }
@@ -187,10 +187,9 @@ void SheetDataContext::onEndElement()
                 if( maFmlaData.mnSharedId >= 0 )
                 {
                     if( mbValidRange && maFmlaData.isValidSharedRef( maCellData.maCellAddr ) )
-                    {
-                        createSharedFormulaMapEntry( maCellData.maCellAddr, maFmlaData.mnSharedId, maFormulaStr );
-                    }
-                    setCellFormula( maCellData.maCellAddr, maFmlaData.mnSharedId );
+                        createSharedFormulaMapEntry(maCellData.maCellAddr, maFmlaData.maFormulaRef, maFmlaData.mnSharedId, maFormulaStr);
+
+                    setCellFormula(maCellData.maCellAddr, maFmlaData.mnSharedId, maCellValue, maCellData.mnCellType);
                     mrSheetData.setCellFormat( maCellData );
                 }
                 else
diff --git a/sc/source/filter/oox/workbookhelper.cxx b/sc/source/filter/oox/workbookhelper.cxx
index 37d5191..8802389 100644
--- a/sc/source/filter/oox/workbookhelper.cxx
+++ b/sc/source/filter/oox/workbookhelper.cxx
@@ -740,7 +740,7 @@ Reference< XSpreadsheetDocument > WorkbookHelper::getDocument() const
     return mrBookGlob.getDocument();
 }
 
-Reference< XSpreadsheet > WorkbookHelper::getSheetFromDoc( sal_Int16 nSheet ) const
+Reference< XSpreadsheet > WorkbookHelper::getSheetFromDoc( sal_Int32 nSheet ) const
 {
     Reference< XSpreadsheet > xSheet;
     try
diff --git a/sc/source/filter/oox/worksheethelper.cxx b/sc/source/filter/oox/worksheethelper.cxx
index bd8b9ba..9fe9144 100644
--- a/sc/source/filter/oox/worksheethelper.cxx
+++ b/sc/source/filter/oox/worksheethelper.cxx
@@ -1602,9 +1602,11 @@ void WorksheetHelper::setCellFormula( const ::com::sun::star::table::CellAddress
     getFormulaBuffer().setCellFormula( rTokenAddress,  rTokenStr );
 }
 
-void WorksheetHelper::setCellFormula( const ::com::sun::star::table::CellAddress& rTokenAddress, sal_Int32 nSharedId )
+void WorksheetHelper::setCellFormula(
+    const ::com::sun::star::table::CellAddress& rAddr, sal_Int32 nSharedId,
+    const OUString& rCellValue, sal_Int32 nValueType )
 {
-    getFormulaBuffer().setCellFormula( rTokenAddress,  nSharedId );
+    getFormulaBuffer().setCellFormula(rAddr, nSharedId, rCellValue, nValueType);
 }
 
 void WorksheetHelper::setCellArrayFormula( const ::com::sun::star::table::CellRangeAddress& rRangeAddress, const ::com::sun::star::table::CellAddress& rTokenAddress, const OUString& rTokenStr )
@@ -1612,9 +1614,10 @@ void WorksheetHelper::setCellArrayFormula( const ::com::sun::star::table::CellRa
     getFormulaBuffer().setCellArrayFormula( rRangeAddress,  rTokenAddress, rTokenStr );
 }
 
-void WorksheetHelper::createSharedFormulaMapEntry(  const ::com::sun::star::table::CellAddress& rAddress, sal_Int32 nSharedId, const OUString& rTokens )
+void WorksheetHelper::createSharedFormulaMapEntry(
+    const table::CellAddress& rAddress, const table::CellRangeAddress& rRange, sal_Int32 nSharedId, const OUString& rTokens )
 {
-    getFormulaBuffer().createSharedFormulaMapEntry( rAddress, nSharedId, rTokens );
+    getFormulaBuffer().createSharedFormulaMapEntry(rAddress, rRange, nSharedId, rTokens);
 }
 
 // ============================================================================
commit 01bc4976a058628a40337f8041c0daedfa63da97
Author: Kohei Yoshida <kohei.yoshida at gmail.com>
Date:   Tue Aug 6 15:40:43 2013 -0400

    Const correctness at ScFormulaCell side.
    
    Though I had to use const_cast in some places...
    
    Change-Id: I22830bf291179efafc1b400f33a520072b7fab0f

diff --git a/sc/inc/formulacell.hxx b/sc/inc/formulacell.hxx
index 3d70200..0d258a0 100644
--- a/sc/inc/formulacell.hxx
+++ b/sc/inc/formulacell.hxx
@@ -248,7 +248,8 @@ public:
     sal_uInt16      GetRawError();  // don't interpret, just return code or result error
     bool GetErrorOrValue( sal_uInt16& rErr, double& rVal );
     sal_uInt8       GetMatrixFlag() const;
-    ScTokenArray*   GetCode() const;
+    ScTokenArray* GetCode();
+    const ScTokenArray* GetCode() const;
 
     bool            IsRunning() const;
     void            SetRunning( bool bVal );
diff --git a/sc/source/core/data/column3.cxx b/sc/source/core/data/column3.cxx
index 25af317..c4276d9 100644
--- a/sc/source/core/data/column3.cxx
+++ b/sc/source/core/data/column3.cxx
@@ -978,7 +978,7 @@ void lcl_AddCode( ScTokenArray& rArr, const ScFormulaCell* pCell )
 {
     rArr.AddOpCode(ocOpen);
 
-    ScTokenArray* pCode = pCell->GetCode();
+    ScTokenArray* pCode = const_cast<ScFormulaCell*>(pCell)->GetCode();
     if (pCode)
     {
         const formula::FormulaToken* pToken = pCode->First();
diff --git a/sc/source/core/data/formulacell.cxx b/sc/source/core/data/formulacell.cxx
index 485d45c..c3ab5cd 100644
--- a/sc/source/core/data/formulacell.cxx
+++ b/sc/source/core/data/formulacell.cxx
@@ -2987,10 +2987,30 @@ void ScFormulaCell::SetChanged(bool b)
     bChanged = b;
 }
 
-sal_uInt8       ScFormulaCell::GetMatrixFlag() const                   { return cMatrixFlag; }
-ScTokenArray*   ScFormulaCell::GetCode() const                         { return pCode; }
-bool            ScFormulaCell::IsRunning() const                       { return bRunning; }
-void            ScFormulaCell::SetRunning( bool bVal )                 { bRunning = bVal; }
+sal_uInt8 ScFormulaCell::GetMatrixFlag() const
+{
+    return cMatrixFlag;
+}
+
+ScTokenArray* ScFormulaCell::GetCode()
+{
+    return pCode;
+}
+
+const ScTokenArray* ScFormulaCell::GetCode() const
+{
+    return pCode;
+}
+
+bool ScFormulaCell::IsRunning() const
+{
+    return bRunning;
+}
+
+void ScFormulaCell::SetRunning( bool bVal )
+{
+    bRunning = bVal;
+}
 
 void ScFormulaCell::CompileDBFormula()
 {
diff --git a/sc/source/filter/excel/xestream.cxx b/sc/source/filter/excel/xestream.cxx
index de764b2..c90719a 100644
--- a/sc/source/filter/excel/xestream.cxx
+++ b/sc/source/filter/excel/xestream.cxx
@@ -845,10 +845,11 @@ OUString XclXmlUtils::ToOUString( const String& s )
     return OUString( s.GetBuffer(), s.Len() );
 }
 
-OUString XclXmlUtils::ToOUString( ScDocument& rDocument, const ScAddress& rAddress,
-        ScTokenArray* pTokenArray, const FormulaCompiler::OpCodeMapPtr & xOpCodeMap )
+OUString XclXmlUtils::ToOUString(
+    ScDocument& rDocument, const ScAddress& rAddress, const ScTokenArray* pTokenArray,
+    const FormulaCompiler::OpCodeMapPtr & xOpCodeMap )
 {
-    ScCompiler aCompiler( &rDocument, rAddress, *pTokenArray);
+    ScCompiler aCompiler( &rDocument, rAddress, const_cast<ScTokenArray&>(*pTokenArray));
     if (xOpCodeMap)
     {
         aCompiler.SetFormulaLanguage( xOpCodeMap );
diff --git a/sc/source/filter/inc/xestream.hxx b/sc/source/filter/inc/xestream.hxx
index 4b37a68..ba759ae 100644
--- a/sc/source/filter/inc/xestream.hxx
+++ b/sc/source/filter/inc/xestream.hxx
@@ -288,7 +288,7 @@ public:
     static OUString ToOUString( const ScfUInt16Vec& rBuffer, sal_Int32 nStart = 0, sal_Int32 nLength = -1 );
     static OUString ToOUString( const String& s );
     static OUString ToOUString( ScDocument& rDocument, const ScAddress& rAddress,
-                                       ScTokenArray* pTokenArray, const ScCompiler::OpCodeMapPtr & xOpCodeMap );
+                                const ScTokenArray* pTokenArray, const ScCompiler::OpCodeMapPtr & xOpCodeMap );
     static OUString ToOUString( const XclExpString& s );
     static const char* ToPsz( bool b );
 
diff --git a/sc/source/ui/unoobj/cellsuno.cxx b/sc/source/ui/unoobj/cellsuno.cxx
index 51a9b8d..528cc9e 100644
--- a/sc/source/ui/unoobj/cellsuno.cxx
+++ b/sc/source/ui/unoobj/cellsuno.cxx
@@ -5176,7 +5176,7 @@ uno::Sequence<sheet::FormulaToken> SAL_CALL ScCellRangeObj::getArrayTokens() thr
         {
             if (aStart1 == aStart2)
             {
-                ScTokenArray* pTokenArray = pFCell1->GetCode();
+                const ScTokenArray* pTokenArray = pFCell1->GetCode();
                 if (pTokenArray)
                     (void)ScTokenConversion::ConvertToTokenSequence(*pDoc, aSequence, *pTokenArray);
             }
commit 492f0ad5347ed640c3a12b61e22d279b29becb88
Author: Kohei Yoshida <kohei.yoshida at gmail.com>
Date:   Tue Aug 6 21:25:50 2013 -0400

    Some cosmetic "fix"
    
    Change-Id: I80baff3b1794619659e505622164e2582e762248

diff --git a/sc/source/filter/inc/formulabuffer.hxx b/sc/source/filter/inc/formulabuffer.hxx
index 984f9c8..1e98060 100644
--- a/sc/source/filter/inc/formulabuffer.hxx
+++ b/sc/source/filter/inc/formulabuffer.hxx
@@ -25,49 +25,46 @@
 #include "sheetdatabuffer.hxx"
 #include <com/sun/star/sheet/XFormulaTokens.hpp>
 
-namespace oox {
-namespace xls {
+namespace oox { namespace xls {
 
 class FormulaBuffer : public WorkbookHelper
 {
-private:
-struct SharedFormulaEntry
-{
-    ::com::sun::star::table::CellAddress maAddress;
-    OUString maTokenStr;
-    sal_Int32 mnSharedId;
-    ::com::sun::star::uno::Reference< ::com::sun::star::sheet::XFormulaTokens > mxFormulaTokens;
-    SharedFormulaEntry( const ::com::sun::star::table::CellAddress& rAddress, const OUString& rTokenStr, sal_Int32 nSharedId ) : maAddress( rAddress ), maTokenStr( rTokenStr ), mnSharedId( nSharedId ) {}
-};
-
+    struct SharedFormulaEntry
+    {
+        ::com::sun::star::table::CellAddress maAddress;
+        OUString maTokenStr;
+        sal_Int32 mnSharedId;
+        ::com::sun::star::uno::Reference< ::com::sun::star::sheet::XFormulaTokens > mxFormulaTokens;
+        SharedFormulaEntry( const ::com::sun::star::table::CellAddress& rAddress, const OUString& rTokenStr, sal_Int32 nSharedId ) : maAddress( rAddress ), maTokenStr( rTokenStr ), mnSharedId( nSharedId ) {}
+    };
 
-struct TokenAddressItem
-{
-    OUString maTokenStr;
-    ::com::sun::star::table::CellAddress maCellAddress;
-    TokenAddressItem( const OUString& rTokenStr, const ::com::sun::star::table::CellAddress& rCellAddress ) : maTokenStr( rTokenStr ), maCellAddress( rCellAddress ) {}
-};
+    struct TokenAddressItem
+    {
+        OUString maTokenStr;
+        ::com::sun::star::table::CellAddress maCellAddress;
+        TokenAddressItem( const OUString& rTokenStr, const ::com::sun::star::table::CellAddress& rCellAddress ) : maTokenStr( rTokenStr ), maCellAddress( rCellAddress ) {}
+    };
 
-struct TokenRangeAddressItem
-{
-    TokenAddressItem maTokenAndAddress;
-    ::com::sun::star::table::CellRangeAddress maCellRangeAddress;
-    TokenRangeAddressItem( const TokenAddressItem& rTokenAndAddress, const ::com::sun::star::table::CellRangeAddress& rCellRangeAddress ) : maTokenAndAddress( rTokenAndAddress ), maCellRangeAddress( rCellRangeAddress ) {}
-};
+    struct TokenRangeAddressItem
+    {
+        TokenAddressItem maTokenAndAddress;
+        ::com::sun::star::table::CellRangeAddress maCellRangeAddress;
+        TokenRangeAddressItem( const TokenAddressItem& rTokenAndAddress, const ::com::sun::star::table::CellRangeAddress& rCellRangeAddress ) : maTokenAndAddress( rTokenAndAddress ), maCellRangeAddress( rCellRangeAddress ) {}
+    };
 
-typedef ::std::map< sal_Int32, std::vector< TokenAddressItem > > FormulaDataMap;
-typedef ::std::map< sal_Int32, std::vector< TokenRangeAddressItem > > ArrayFormulaDataMap;
-// shared formuala descriptions, the id and address the formula is at
-typedef std::pair< ::com::sun::star::table::CellAddress, sal_Int32 > SharedFormulaDesc;
-// sheet -> list of shared formula descriptions
-typedef ::std::map< sal_Int32, std::vector< SharedFormulaDesc > > SheetToSharedFormulaid;
-// sheet -> stuff needed to create shared formulae
-typedef ::std::map< sal_Int32, std::vector< SharedFormulaEntry > >  SheetToFormulaEntryMap;
-// sharedId -> tokedId
-typedef ::std::map< sal_Int32, sal_Int32 > SharedIdToTokenIndex;
-typedef ::std::map< sal_Int32, SharedIdToTokenIndex > SheetToSharedIdToTokenIndex;

... etc. - the rest is truncated


More information about the Libreoffice-commits mailing list