summaryrefslogtreecommitdiff
path: root/sc/source/filter/oox/formulabuffer.cxx
blob: 21e383fe97b7da6d85a56680b04eab01921cf8d9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
/* -*- 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 "formulabuffer.hxx"
#include "formulaparser.hxx"
#include <com/sun/star/sheet/XFormulaTokens.hpp>
#include <com/sun/star/sheet/XArrayFormulaTokens.hpp>
#include <com/sun/star/container/XIndexAccess.hpp>
#include <com/sun/star/sheet/XSpreadsheetDocument.hpp>
#include <com/sun/star/table/XCell2.hpp>
#include "formulacell.hxx"
#include "document.hxx"
#include "convuno.hxx"

#include "rangelst.hxx"
#include "autonamecache.hxx"
#include "tokenuno.hxx"
#include "tokenarray.hxx"
#include "sharedformulagroups.hxx"
#include "oox/token/tokens.hxx"

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::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::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 )
{
}

void FormulaBuffer::finalizeImport()
{
    ISegmentProgressBarRef xFormulaBar = getProgressBar().createSegment( getProgressBar().getFreeLength() );

    ScDocument& rDoc = getScDocument();
    Reference< XIndexAccess > xSheets( getDocument()->getSheets(), UNO_QUERY_THROW );
    rDoc.SetAutoNameCache( new ScAutoNameCache( &rDoc ) );
    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 );

        applySharedFormulas(nTab);

        FormulaDataMap::iterator cellIt = maCellFormulas.find( nTab );
        if ( cellIt != maCellFormulas.end() )
        {
            applyCellFormulas( cellIt->second );
        }

        ArrayFormulaDataMap::iterator itArray = maCellArrayFormulas.find( nTab );
        if ( itArray != maCellArrayFormulas.end() )
        {
            applyArrayFormulas( itArray->second );
        }

        FormulaValueMap::iterator itValues = maCellFormulaValues.find( nTab );
        if ( itValues != maCellFormulaValues.end() )
        {
            std::vector< ValueAddressPair > & rVector = itValues->second;
            applyCellFormulaValues( rVector );
        }
    }
    rDoc.SetAutoNameCache( NULL );
    xFormulaBar->setPosition( 1.0 );
}

void FormulaBuffer::applyCellFormula( ScDocument& rDoc, const ApiTokenSequence& rTokens, const ::com::sun::star::table::CellAddress& rAddress )
{
    ScTokenArray aTokenArray;
    ScAddress aCellPos;
    ScUnoConversion::FillScAddress( aCellPos, rAddress );
    ScTokenConversion::ConvertToTokenArray( rDoc, aTokenArray, rTokens );
    ScFormulaCell* pNewCell = new ScFormulaCell( &rDoc, aCellPos, &aTokenArray );
    pNewCell->StartListeningTo( &rDoc );
    rDoc.EnsureTable(aCellPos.Tab());
    rDoc.SetFormulaCell(aCellPos, pNewCell);
}

void FormulaBuffer::applyCellFormulas( const std::vector< TokenAddressItem >& rVector )
{
    ScDocument& rDoc = getScDocument();
    for ( std::vector< TokenAddressItem >::const_iterator it = rVector.begin(), it_end = rVector.end(); it != it_end; ++it )
    {
        const ::com::sun::star::table::CellAddress& rAddress = it->maCellAddress;
        ApiTokenSequence aTokens = getFormulaParser().importFormula( rAddress, it->maTokenStr );
        applyCellFormula( rDoc, aTokens, rAddress );
    }
}

void FormulaBuffer::applyCellFormulaValues( const std::vector< ValueAddressPair >& rVector )
{
    ScDocument& rDoc = getScDocument();
    for ( std::vector< ValueAddressPair >::const_iterator it = rVector.begin(), it_end = rVector.end(); it != it_end; ++it )
    {
        ScAddress aCellPos;
        ScUnoConversion::FillScAddress( aCellPos, it->first );
        ScFormulaCell* pCell = rDoc.GetFormulaCell(aCellPos);
        if (pCell)
        {
            pCell->SetHybridDouble( it->second );
            pCell->ResetDirty();
            pCell->SetChanged(false);
        }
    }
}

void FormulaBuffer::applySharedFormulas( sal_Int32 nTab )
{
    SheetToFormulaEntryMap::const_iterator itShared = maSharedFormulas.find(nTab);
    if (itShared == maSharedFormulas.end())
        // There is no shared formulas for this sheet.
        return;

    SheetToSharedFormulaid::const_iterator itCells = maSharedFormulaIds.find(nTab);
    if (itCells == maSharedFormulaIds.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();

    sc::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 = 1; // Length gets updated as we go.
                    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);
            if (xGroup->mnStart == aPos.Row())
                // Generate code for the top cell only.
                xGroup->compileCode(rDoc, aPos, formula::FormulaGrammar::GRAM_DEFAULT);
            ScFormulaCell* pCell = new ScFormulaCell(&rDoc, aPos, xGroup);

            bool bInserted = rDoc.SetGroupFormulaCell(aPos, pCell);
            if (!bInserted)
            {
                // Insertion failed.
                delete pCell;
                continue;
            }

            // Update the length of shared formula span as we go. The length
            // that Excel gives is not always correct.
            xGroup->mnLength = aPos.Row() - xGroup->mnStart + 1;
            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);
            }
        }
    }
}

void FormulaBuffer::applyArrayFormulas( const std::vector< TokenRangeAddressItem >& rVector )
{
    ScDocument& rDoc = getScDocument();
    std::vector<TokenRangeAddressItem>::const_iterator it = rVector.begin(), itEnd = rVector.end();
    for (; it != itEnd; ++it)
    {
        ScAddress aPos;
        ScUnoConversion::FillScAddress(aPos, it->maTokenAndAddress.maCellAddress);
        ScRange aRange;
        ScUnoConversion::FillScRange(aRange, it->maCellRangeAddress);

        ScCompiler aComp(&rDoc, aPos);
        aComp.SetGrammar(formula::FormulaGrammar::GRAM_ENGLISH_XL_OOX);
        ScTokenArray* pArray = aComp.CompileString(it->maTokenAndAddress.maTokenStr);
        if (pArray)
        {
            ScMarkData aMark;
            aMark.SelectOneTable(aPos.Tab());
            rDoc.InsertMatrixFormula(
                aRange.aStart.Col(), aRange.aStart.Row(), aRange.aEnd.Col(), aRange.aEnd.Row(),
                aMark, it->maTokenAndAddress.maTokenStr, pArray, formula::FormulaGrammar::GRAM_ENGLISH_XL_OOX);

            ScFormulaCell* pFC = rDoc.GetFormulaCell(aPos);
            if (pFC)
                pFC->StartListeningTo(&rDoc);
        }
    }
}

void FormulaBuffer::createSharedFormulaMapEntry(
    const table::CellAddress& rAddress, const table::CellRangeAddress& rRange,
    sal_Int32 nSharedId, const OUString& rTokens )
{
    std::vector<SharedFormulaEntry>& rSharedFormulas = maSharedFormulas[ rAddress.Sheet ];
    SharedFormulaEntry aEntry(rAddress, rRange, rTokens, nSharedId);
    rSharedFormulas.push_back( aEntry );
}

void FormulaBuffer::setCellFormula( const ::com::sun::star::table::CellAddress& rAddress, const OUString& rTokenStr )
{
    maCellFormulas[ rAddress.Sheet ].push_back( TokenAddressItem( rTokenStr, rAddress ) );
}

void FormulaBuffer::setCellFormula(
    const table::CellAddress& rAddress, sal_Int32 nSharedId, const OUString& rCellValue, sal_Int32 nValueType )
{
    maSharedFormulaIds[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 )
{

    TokenAddressItem tokenPair( rTokenStr, rTokenAddress );
    maCellArrayFormulas[ rRangeAddress.Sheet ].push_back( TokenRangeAddressItem( tokenPair, rRangeAddress ) );
}

void FormulaBuffer::setCellFormulaValue( const ::com::sun::star::table::CellAddress& rAddress, double fValue )
{
    maCellFormulaValues[ rAddress.Sheet ].push_back( ValueAddressPair( rAddress, fValue ) );
}

}}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */