1 /**************************************************************
2 *
3 * Licensed to the Apache Software Foundation (ASF) under one
4 * or more contributor license agreements. See the NOTICE file
5 * distributed with this work for additional information
6 * regarding copyright ownership. The ASF licenses this file
7 * to you under the Apache License, Version 2.0 (the
8 * "License"); you may not use this file except in compliance
9 * with the License. You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing,
14 * software distributed under the License is distributed on an
15 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16 * KIND, either express or implied. See the License for the
17 * specific language governing permissions and limitations
18 * under the License.
19 *
20 *************************************************************/
21
22
23
24 // MARKER(update_precomp.py): autogen include statement, do not remove
25 #include "precompiled_sc.hxx"
26
27
28
29 // INCLUDE ---------------------------------------------------------------
30
31 #include "externalrefmgr.hxx"
32 #include "document.hxx"
33 #include "token.hxx"
34 #include "tokenarray.hxx"
35 #include "address.hxx"
36 #include "tablink.hxx"
37 #include "docsh.hxx"
38 #include "scextopt.hxx"
39 #include "rangenam.hxx"
40 #include "cell.hxx"
41 #include "viewdata.hxx"
42 #include "tabvwsh.hxx"
43 #include "sc.hrc"
44
45 #include "sfx2/app.hxx"
46 #include "sfx2/docfilt.hxx"
47 #include "sfx2/docfile.hxx"
48 #include "sfx2/fcontnr.hxx"
49 #include "sfx2/sfxsids.hrc"
50 #include "sfx2/objsh.hxx"
51 #include "svl/broadcast.hxx"
52 #include "svl/smplhint.hxx"
53 #include "svl/itemset.hxx"
54 #include "svl/stritem.hxx"
55 #include "svl/urihelper.hxx"
56 #include "svl/zformat.hxx"
57 #include "sfx2/linkmgr.hxx"
58 #include "tools/urlobj.hxx"
59 #include "unotools/ucbhelper.hxx"
60 #include "unotools/localfilehelper.hxx"
61
62 #include <memory>
63 #include <algorithm>
64
65 #include <boost/scoped_ptr.hpp>
66
67 using ::std::unique_ptr;
68 using ::com::sun::star::uno::Any;
69 using ::rtl::OUString;
70 using ::std::vector;
71 using ::std::find;
72 using ::std::find_if;
73 using ::std::for_each;
74 using ::std::distance;
75 using ::std::pair;
76 using ::std::list;
77 using namespace formula;
78
79 #define SRCDOC_LIFE_SPAN 6000 // 1 minute (in 100th of a sec)
80 #define SRCDOC_SCAN_INTERVAL 1000*5 // every 5 seconds (in msec)
81
82 namespace {
83
84 class TabNameSearchPredicate
85 {
86 public:
87 typedef ScExternalRefCache::TableName argument_type;
88 typedef bool result_type;
TabNameSearchPredicate(const String & rSearchName)89 explicit TabNameSearchPredicate(const String& rSearchName) :
90 maSearchName(ScGlobal::pCharClass->upper(rSearchName))
91 {
92 }
93
operator ()(const ScExternalRefCache::TableName & rTabNameSet) const94 bool operator()(const ScExternalRefCache::TableName& rTabNameSet) const
95 {
96 // Ok, I'm doing case insensitive search here.
97 return rTabNameSet.maUpperName.Equals(maSearchName);
98 }
99
100 private:
101 String maSearchName;
102 };
103
104 class FindSrcFileByName
105 {
106 public:
107 typedef ScExternalRefManager::SrcFileData argument_type;
108 typedef bool result_type;
FindSrcFileByName(const String & rMatchName)109 FindSrcFileByName(const String& rMatchName) :
110 mrMatchName(rMatchName)
111 {
112 }
113
operator ()(const ScExternalRefManager::SrcFileData & rSrcData) const114 bool operator()(const ScExternalRefManager::SrcFileData& rSrcData) const
115 {
116 return rSrcData.maFileName.Equals(mrMatchName);
117 }
118
119 private:
120 const String& mrMatchName;
121 };
122
123 class NotifyLinkListener
124 {
125 public:
126 typedef ScExternalRefManager::LinkListener* argument_type;
127 typedef void result_type;
NotifyLinkListener(sal_uInt16 nFileId,ScExternalRefManager::LinkUpdateType eType)128 NotifyLinkListener(sal_uInt16 nFileId, ScExternalRefManager::LinkUpdateType eType) :
129 mnFileId(nFileId), meType(eType) {}
130
NotifyLinkListener(const NotifyLinkListener & r)131 NotifyLinkListener(const NotifyLinkListener& r) :
132 mnFileId(r.mnFileId), meType(r.meType) {}
133
operator ()(ScExternalRefManager::LinkListener * p) const134 void operator() (ScExternalRefManager::LinkListener* p) const
135 {
136 p->notify(mnFileId, meType);
137 }
138 private:
139 sal_uInt16 mnFileId;
140 ScExternalRefManager::LinkUpdateType meType;
141 };
142
143 struct UpdateFormulaCell
144 {
145 typedef ScFormulaCell* argument_type;
146 typedef void result_type;
operator ()__anon665b078c0111::UpdateFormulaCell147 void operator() (ScFormulaCell* pCell) const
148 {
149 // Check to make sure the cell really contains ocExternalRef.
150 // External names, external cell and range references all have a
151 // ocExternalRef token.
152 const ScTokenArray* pCode = pCell->GetCode();
153 if (!pCode->HasOpCode( ocExternalRef))
154 return;
155
156 ScTokenArray* pArray = pCell->GetCode();
157 if (pArray)
158 // Clear the error code, or a cell with error won't get re-compiled.
159 pArray->SetCodeError(0);
160
161 pCell->SetCompile(true);
162 pCell->CompileTokenArray();
163 pCell->SetDirty();
164 }
165 };
166
167 class RemoveFormulaCell
168 {
169 public:
170 typedef pair<const sal_uInt16, ScExternalRefManager::RefCellSet> argument_type;
171 typedef void result_type;
RemoveFormulaCell(ScFormulaCell * p)172 explicit RemoveFormulaCell(ScFormulaCell* p) : mpCell(p) {}
operator ()(pair<const sal_uInt16,ScExternalRefManager::RefCellSet> & r) const173 void operator() (pair<const sal_uInt16, ScExternalRefManager::RefCellSet>& r) const
174 {
175 r.second.erase(mpCell);
176 }
177 private:
178 ScFormulaCell* mpCell;
179 };
180
181 class ConvertFormulaToStatic
182 {
183 public:
184 typedef ScFormulaCell* argument_type;
185 typedef void result_type;
ConvertFormulaToStatic(ScDocument * pDoc)186 explicit ConvertFormulaToStatic(ScDocument* pDoc) : mpDoc(pDoc) {}
operator ()(ScFormulaCell * pCell) const187 void operator() (ScFormulaCell* pCell) const
188 {
189 ScAddress aPos = pCell->aPos;
190
191 // We don't check for empty cells because empty external cells are
192 // treated as having a value of 0.
193
194 if (pCell->IsValue())
195 {
196 // Turn this into value cell.
197 double fVal = pCell->GetValue();
198 mpDoc->PutCell(aPos, new ScValueCell(fVal));
199 }
200 else
201 {
202 // string cell otherwise.
203 String aVal;
204 pCell->GetString(aVal);
205 mpDoc->PutCell(aPos, new ScStringCell(aVal));
206 }
207 }
208 private:
209 ScDocument* mpDoc;
210 };
211
212 }
213
214 // ============================================================================
215
Table()216 ScExternalRefCache::Table::Table()
217 : meReferenced( REFERENCED_MARKED )
218 // Prevent accidental data loss due to lack of knowledge.
219 {
220 }
221
~Table()222 ScExternalRefCache::Table::~Table()
223 {
224 }
225
setReferencedFlag(ScExternalRefCache::Table::ReferencedFlag eFlag)226 void ScExternalRefCache::Table::setReferencedFlag( ScExternalRefCache::Table::ReferencedFlag eFlag )
227 {
228 meReferenced = eFlag;
229 }
230
setReferenced(bool bReferenced)231 void ScExternalRefCache::Table::setReferenced( bool bReferenced )
232 {
233 if (meReferenced != REFERENCED_PERMANENT)
234 meReferenced = (bReferenced ? REFERENCED_MARKED : UNREFERENCED);
235 }
236
getReferencedFlag() const237 ScExternalRefCache::Table::ReferencedFlag ScExternalRefCache::Table::getReferencedFlag() const
238 {
239 return meReferenced;
240 }
241
isReferenced() const242 bool ScExternalRefCache::Table::isReferenced() const
243 {
244 return meReferenced != UNREFERENCED;
245 }
246
setCell(SCCOL nCol,SCROW nRow,TokenRef pToken,sal_uInt32 nFmtIndex,bool bSetCacheRange)247 void ScExternalRefCache::Table::setCell(SCCOL nCol, SCROW nRow, TokenRef pToken, sal_uInt32 nFmtIndex, bool bSetCacheRange)
248 {
249 using ::std::pair;
250 RowsDataType::iterator itrRow = maRows.find(nRow);
251 if (itrRow == maRows.end())
252 {
253 // This row does not exist yet.
254 pair<RowsDataType::iterator, bool> res = maRows.insert(
255 RowsDataType::value_type(nRow, RowDataType()));
256
257 if (!res.second)
258 return;
259
260 itrRow = res.first;
261 }
262
263 // Insert this token into the specified column location. I don't need to
264 // check for existing data. Just overwrite it.
265 RowDataType& rRow = itrRow->second;
266 ScExternalRefCache::Cell aCell;
267 aCell.mxToken = pToken;
268 aCell.mnFmtIndex = nFmtIndex;
269 rRow.insert(RowDataType::value_type(nCol, aCell));
270 if (bSetCacheRange)
271 setCachedCell(nCol, nRow);
272 }
273
getCell(SCCOL nCol,SCROW nRow,sal_uInt32 * pnFmtIndex) const274 ScExternalRefCache::TokenRef ScExternalRefCache::Table::getCell(SCCOL nCol, SCROW nRow, sal_uInt32* pnFmtIndex) const
275 {
276 RowsDataType::const_iterator itrTable = maRows.find(nRow);
277 if (itrTable == maRows.end())
278 {
279 // this table doesn't have the specified row.
280 return getEmptyOrNullToken(nCol, nRow);
281 }
282
283 const RowDataType& rRowData = itrTable->second;
284 RowDataType::const_iterator itrRow = rRowData.find(nCol);
285 if (itrRow == rRowData.end())
286 {
287 // this row doesn't have the specified column.
288 return getEmptyOrNullToken(nCol, nRow);
289 }
290
291 const Cell& rCell = itrRow->second;
292 if (pnFmtIndex)
293 *pnFmtIndex = rCell.mnFmtIndex;
294
295 return rCell.mxToken;
296 }
297
hasRow(SCROW nRow) const298 bool ScExternalRefCache::Table::hasRow( SCROW nRow ) const
299 {
300 RowsDataType::const_iterator itrRow = maRows.find(nRow);
301 return itrRow != maRows.end();
302 }
303
getAllRows(vector<SCROW> & rRows,SCROW nLow,SCROW nHigh) const304 void ScExternalRefCache::Table::getAllRows(vector<SCROW>& rRows, SCROW nLow, SCROW nHigh) const
305 {
306 vector<SCROW> aRows;
307 aRows.reserve(maRows.size());
308 RowsDataType::const_iterator itr = maRows.begin(), itrEnd = maRows.end();
309 for (; itr != itrEnd; ++itr)
310 if (nLow <= itr->first && itr->first <= nHigh)
311 aRows.push_back(itr->first);
312
313 // hash map is not ordered, so we need to explicitly sort it.
314 ::std::sort(aRows.begin(), aRows.end());
315 rRows.swap(aRows);
316 }
317
getRowRange() const318 ::std::pair< SCROW, SCROW > ScExternalRefCache::Table::getRowRange() const
319 {
320 ::std::pair< SCROW, SCROW > aRange( 0, 0 );
321 if( !maRows.empty() )
322 {
323 // iterate over entire container (hash map is not sorted by key)
324 RowsDataType::const_iterator itr = maRows.begin(), itrEnd = maRows.end();
325 aRange.first = itr->first;
326 aRange.second = itr->first + 1;
327 while( ++itr != itrEnd )
328 {
329 if( itr->first < aRange.first )
330 aRange.first = itr->first;
331 else if( itr->first >= aRange.second )
332 aRange.second = itr->first + 1;
333 }
334 }
335 return aRange;
336 }
337
getAllCols(SCROW nRow,vector<SCCOL> & rCols,SCCOL nLow,SCCOL nHigh) const338 void ScExternalRefCache::Table::getAllCols(SCROW nRow, vector<SCCOL>& rCols, SCCOL nLow, SCCOL nHigh) const
339 {
340 RowsDataType::const_iterator itrRow = maRows.find(nRow);
341 if (itrRow == maRows.end())
342 // this table doesn't have the specified row.
343 return;
344
345 const RowDataType& rRowData = itrRow->second;
346 vector<SCCOL> aCols;
347 aCols.reserve(rRowData.size());
348 RowDataType::const_iterator itrCol = rRowData.begin(), itrColEnd = rRowData.end();
349 for (; itrCol != itrColEnd; ++itrCol)
350 if (nLow <= itrCol->first && itrCol->first <= nHigh)
351 aCols.push_back(itrCol->first);
352
353 // hash map is not ordered, so we need to explicitly sort it.
354 ::std::sort(aCols.begin(), aCols.end());
355 rCols.swap(aCols);
356 }
357
getColRange(SCROW nRow) const358 ::std::pair< SCCOL, SCCOL > ScExternalRefCache::Table::getColRange( SCROW nRow ) const
359 {
360 ::std::pair< SCCOL, SCCOL > aRange( 0, 0 );
361
362 RowsDataType::const_iterator itrRow = maRows.find( nRow );
363 if (itrRow == maRows.end())
364 // this table doesn't have the specified row.
365 return aRange;
366
367 const RowDataType& rRowData = itrRow->second;
368 if( !rRowData.empty() )
369 {
370 // iterate over entire container (hash map is not sorted by key)
371 RowDataType::const_iterator itr = rRowData.begin(), itrEnd = rRowData.end();
372 aRange.first = itr->first;
373 aRange.second = itr->first + 1;
374 while( ++itr != itrEnd )
375 {
376 if( itr->first < aRange.first )
377 aRange.first = itr->first;
378 else if( itr->first >= aRange.second )
379 aRange.second = itr->first + 1;
380 }
381 }
382 return aRange;
383 }
384
getAllNumberFormats(vector<sal_uInt32> & rNumFmts) const385 void ScExternalRefCache::Table::getAllNumberFormats(vector<sal_uInt32>& rNumFmts) const
386 {
387 RowsDataType::const_iterator itrRow = maRows.begin(), itrRowEnd = maRows.end();
388 for (; itrRow != itrRowEnd; ++itrRow)
389 {
390 const RowDataType& rRowData = itrRow->second;
391 RowDataType::const_iterator itrCol = rRowData.begin(), itrColEnd = rRowData.end();
392 for (; itrCol != itrColEnd; ++itrCol)
393 {
394 const Cell& rCell = itrCol->second;
395 rNumFmts.push_back(rCell.mnFmtIndex);
396 }
397 }
398 }
399
getCachedRanges() const400 const ScRangeList& ScExternalRefCache::Table::getCachedRanges() const
401 {
402 return maCachedRanges;
403 }
404
isRangeCached(SCCOL nCol1,SCROW nRow1,SCCOL nCol2,SCROW nRow2) const405 bool ScExternalRefCache::Table::isRangeCached(SCCOL nCol1, SCROW nRow1, SCCOL nCol2, SCROW nRow2) const
406 {
407 return maCachedRanges.In(ScRange(nCol1, nRow1, 0, nCol2, nRow2, 0));
408 }
409
setCachedCell(SCCOL nCol,SCROW nRow)410 void ScExternalRefCache::Table::setCachedCell(SCCOL nCol, SCROW nRow)
411 {
412 setCachedCellRange(nCol, nRow, nCol, nRow);
413 }
414
setCachedCellRange(SCCOL nCol1,SCROW nRow1,SCCOL nCol2,SCROW nRow2)415 void ScExternalRefCache::Table::setCachedCellRange(SCCOL nCol1, SCROW nRow1, SCCOL nCol2, SCROW nRow2)
416 {
417 ScRange aRange(nCol1, nRow1, 0, nCol2, nRow2, 0);
418 if (!maCachedRanges.Count())
419 maCachedRanges.Append(aRange);
420 else
421 maCachedRanges.Join(aRange);
422
423 String aStr;
424 maCachedRanges.Format(aStr, SCA_VALID);
425 }
426
setWholeTableCached()427 void ScExternalRefCache::Table::setWholeTableCached()
428 {
429 setCachedCellRange(0, 0, MAXCOL, MAXROW);
430 }
431
isInCachedRanges(SCCOL nCol,SCROW nRow) const432 bool ScExternalRefCache::Table::isInCachedRanges(SCCOL nCol, SCROW nRow) const
433 {
434 return maCachedRanges.In(ScRange(nCol, nRow, 0, nCol, nRow, 0));
435 }
436
getEmptyOrNullToken(SCCOL nCol,SCROW nRow) const437 ScExternalRefCache::TokenRef ScExternalRefCache::Table::getEmptyOrNullToken(
438 SCCOL nCol, SCROW nRow) const
439 {
440 if (isInCachedRanges(nCol, nRow))
441 {
442 TokenRef p(new ScEmptyCellToken(false, false));
443 return p;
444 }
445 return TokenRef();
446 }
447
448 // ----------------------------------------------------------------------------
449
TableName(const String & rUpper,const String & rReal)450 ScExternalRefCache::TableName::TableName(const String& rUpper, const String& rReal) :
451 maUpperName(rUpper), maRealName(rReal)
452 {
453 }
454
455 // ----------------------------------------------------------------------------
456
CellFormat()457 ScExternalRefCache::CellFormat::CellFormat() :
458 mbIsSet(false), mnType(NUMBERFORMAT_ALL), mnIndex(0)
459 {
460 }
461
462 // ----------------------------------------------------------------------------
463
ScExternalRefCache()464 ScExternalRefCache::ScExternalRefCache()
465 {
466 }
~ScExternalRefCache()467 ScExternalRefCache::~ScExternalRefCache()
468 {
469 }
470
getRealTableName(sal_uInt16 nFileId,const String & rTabName) const471 const String* ScExternalRefCache::getRealTableName(sal_uInt16 nFileId, const String& rTabName) const
472 {
473 DocDataType::const_iterator itrDoc = maDocs.find(nFileId);
474 if (itrDoc == maDocs.end())
475 {
476 // specified document is not cached.
477 return NULL;
478 }
479
480 const DocItem& rDoc = itrDoc->second;
481 TableNameIndexMap::const_iterator itrTabId = rDoc.maTableNameIndex.find(
482 ScGlobal::pCharClass->upper(rTabName));
483 if (itrTabId == rDoc.maTableNameIndex.end())
484 {
485 // the specified table is not in cache.
486 return NULL;
487 }
488
489 return &rDoc.maTableNames[itrTabId->second].maRealName;
490 }
491
getRealRangeName(sal_uInt16 nFileId,const String & rRangeName) const492 const String* ScExternalRefCache::getRealRangeName(sal_uInt16 nFileId, const String& rRangeName) const
493 {
494 DocDataType::const_iterator itrDoc = maDocs.find(nFileId);
495 if (itrDoc == maDocs.end())
496 {
497 // specified document is not cached.
498 return NULL;
499 }
500
501 const DocItem& rDoc = itrDoc->second;
502 NamePairMap::const_iterator itr = rDoc.maRealRangeNameMap.find(
503 ScGlobal::pCharClass->upper(rRangeName));
504 if (itr == rDoc.maRealRangeNameMap.end())
505 // range name not found.
506 return NULL;
507
508 return &itr->second;
509 }
510
getCellData(sal_uInt16 nFileId,const String & rTabName,SCCOL nCol,SCROW nRow,sal_uInt32 * pnFmtIndex)511 ScExternalRefCache::TokenRef ScExternalRefCache::getCellData(
512 sal_uInt16 nFileId, const String& rTabName, SCCOL nCol, SCROW nRow, sal_uInt32* pnFmtIndex)
513 {
514 DocDataType::const_iterator itrDoc = maDocs.find(nFileId);
515 if (itrDoc == maDocs.end())
516 {
517 // specified document is not cached.
518 return TokenRef();
519 }
520
521 const DocItem& rDoc = itrDoc->second;
522 TableNameIndexMap::const_iterator itrTabId = rDoc.maTableNameIndex.find(
523 ScGlobal::pCharClass->upper(rTabName));
524 if (itrTabId == rDoc.maTableNameIndex.end())
525 {
526 // the specified table is not in cache.
527 return TokenRef();
528 }
529
530 const TableTypeRef& pTableData = rDoc.maTables[itrTabId->second];
531 if (!pTableData.get())
532 {
533 // the table data is not instantiated yet.
534 return TokenRef();
535 }
536
537 return pTableData->getCell(nCol, nRow, pnFmtIndex);
538 }
539
getCellRangeData(sal_uInt16 nFileId,const String & rTabName,const ScRange & rRange)540 ScExternalRefCache::TokenArrayRef ScExternalRefCache::getCellRangeData(
541 sal_uInt16 nFileId, const String& rTabName, const ScRange& rRange)
542 {
543 DocDataType::iterator itrDoc = maDocs.find(nFileId);
544 if (itrDoc == maDocs.end())
545 // specified document is not cached.
546 return TokenArrayRef();
547
548 DocItem& rDoc = itrDoc->second;
549
550 TableNameIndexMap::iterator itrTabId = rDoc.maTableNameIndex.find(
551 ScGlobal::pCharClass->upper(rTabName));
552 if (itrTabId == rDoc.maTableNameIndex.end())
553 // the specified table is not in cache.
554 return TokenArrayRef();
555
556 const ScAddress& s = rRange.aStart;
557 const ScAddress& e = rRange.aEnd;
558
559 SCTAB nTab1 = s.Tab(), nTab2 = e.Tab();
560 SCCOL nCol1 = s.Col(), nCol2 = e.Col();
561 SCROW nRow1 = s.Row(), nRow2 = e.Row();
562
563 // Make sure I have all the tables cached.
564 size_t nTabFirstId = itrTabId->second;
565 size_t nTabLastId = nTabFirstId + nTab2 - nTab1;
566 if (nTabLastId >= rDoc.maTables.size())
567 // not all tables are cached.
568 return TokenArrayRef();
569
570 ScRange aCacheRange( nCol1, nRow1, static_cast<SCTAB>(nTabFirstId), nCol2, nRow2, static_cast<SCTAB>(nTabLastId));
571
572 RangeArrayMap::const_iterator itrRange = rDoc.maRangeArrays.find( aCacheRange);
573 if (itrRange != rDoc.maRangeArrays.end())
574 // Cache hit!
575 return itrRange->second;
576
577 ::boost::scoped_ptr<ScRange> pNewRange;
578 TokenArrayRef pArray;
579 bool bFirstTab = true;
580 for (size_t nTab = nTabFirstId; nTab <= nTabLastId; ++nTab)
581 {
582 TableTypeRef pTab = rDoc.maTables[nTab];
583 if (!pTab.get())
584 return TokenArrayRef();
585
586 SCCOL nDataCol1 = nCol1, nDataCol2 = nCol2;
587 SCROW nDataRow1 = nRow1, nDataRow2 = nRow2;
588
589 if (!pTab->isRangeCached(nDataCol1, nDataRow1, nDataCol2, nDataRow2))
590 {
591 // specified range is not entirely within cached ranges.
592 return TokenArrayRef();
593 }
594
595 ScMatrixRef xMat = new ScMatrix(
596 static_cast<SCSIZE>(nDataCol2-nDataCol1+1), static_cast<SCSIZE>(nDataRow2-nDataRow1+1));
597
598 #if 0
599 // TODO: Switch to this code block once we have support for sparsely-filled
600 // matrices in ScMatrix.
601
602 // Only fill non-empty cells, for better performance.
603 vector<SCROW> aRows;
604 pTab->getAllRows(aRows, nDataRow1, nDataRow2);
605 for (vector<SCROW>::const_iterator itr = aRows.begin(), itrEnd = aRows.end(); itr != itrEnd; ++itr)
606 {
607 SCROW nRow = *itr;
608 vector<SCCOL> aCols;
609 pTab->getAllCols(nRow, aCols, nDataCol1, nDataCol2);
610 for (vector<SCCOL>::const_iterator itrCol = aCols.begin(), itrColEnd = aCols.end(); itrCol != itrColEnd; ++itrCol)
611 {
612 SCCOL nCol = *itrCol;
613 TokenRef pToken = pTab->getCell(nCol, nRow);
614 if (!pToken)
615 // This should never happen!
616 return TokenArrayRef();
617
618 SCSIZE nC = nCol - nDataCol1, nR = nRow - nDataRow1;
619 switch (pToken->GetType())
620 {
621 case svDouble:
622 xMat->PutDouble(pToken->GetDouble(), nC, nR);
623 break;
624 case svString:
625 xMat->PutString(pToken->GetString(), nC, nR);
626 break;
627 default:
628 ;
629 }
630 }
631 }
632 #else
633 vector<SCROW> aRows;
634 pTab->getAllRows(aRows, nDataRow1, nDataRow2);
635 if (aRows.empty())
636 // Cache is empty.
637 return TokenArrayRef();
638 else
639 // Trim the column below the last non-empty row.
640 nDataRow2 = aRows.back();
641
642 // Empty all matrix elements first, and fill only non-empty elements.
643 for (SCROW nRow = nDataRow1; nRow <= nDataRow2; ++nRow)
644 {
645 for (SCCOL nCol = nDataCol1; nCol <= nDataCol2; ++nCol)
646 {
647 TokenRef pToken = pTab->getCell(nCol, nRow);
648 SCSIZE nC = nCol - nCol1, nR = nRow - nRow1;
649 if (!pToken)
650 return TokenArrayRef();
651
652 switch (pToken->GetType())
653 {
654 case svDouble:
655 xMat->PutDouble(pToken->GetDouble(), nC, nR);
656 break;
657 case svString:
658 xMat->PutString(pToken->GetString(), nC, nR);
659 break;
660 default:
661 xMat->PutEmpty(nC, nR);
662 }
663 }
664 }
665 #endif
666
667 if (!bFirstTab)
668 pArray->AddOpCode(ocSep);
669
670 ScMatrix* pMat2 = xMat;
671 ScMatrixToken aToken(pMat2);
672 if (!pArray)
673 pArray.reset(new ScTokenArray);
674 pArray->AddToken(aToken);
675
676 bFirstTab = false;
677
678 if (!pNewRange)
679 pNewRange.reset(new ScRange(nDataCol1, nDataRow1, 0, nDataCol2, nDataRow2, 0));
680 else
681 pNewRange->ExtendTo(ScRange(nDataCol1, nDataRow1, 0, nDataCol2, nDataRow2, 0));
682 }
683
684 if (pNewRange)
685 rDoc.maRangeArrays.insert( RangeArrayMap::value_type(*pNewRange, pArray));
686 return pArray;
687 }
688
getRangeNameTokens(sal_uInt16 nFileId,const String & rName)689 ScExternalRefCache::TokenArrayRef ScExternalRefCache::getRangeNameTokens(sal_uInt16 nFileId, const String& rName)
690 {
691 DocItem* pDoc = getDocItem(nFileId);
692 if (!pDoc)
693 return TokenArrayRef();
694
695 RangeNameMap& rMap = pDoc->maRangeNames;
696 RangeNameMap::const_iterator itr = rMap.find(
697 ScGlobal::pCharClass->upper(rName));
698 if (itr == rMap.end())
699 return TokenArrayRef();
700
701 return itr->second;
702 }
703
setRangeNameTokens(sal_uInt16 nFileId,const String & rName,TokenArrayRef pArray)704 void ScExternalRefCache::setRangeNameTokens(sal_uInt16 nFileId, const String& rName, TokenArrayRef pArray)
705 {
706 DocItem* pDoc = getDocItem(nFileId);
707 if (!pDoc)
708 return;
709
710 String aUpperName = ScGlobal::pCharClass->upper(rName);
711 RangeNameMap& rMap = pDoc->maRangeNames;
712 rMap.insert(RangeNameMap::value_type(aUpperName, pArray));
713 pDoc->maRealRangeNameMap.insert(NamePairMap::value_type(aUpperName, rName));
714 }
715
setCellData(sal_uInt16 nFileId,const String & rTabName,SCCOL nCol,SCROW nRow,TokenRef pToken,sal_uInt32 nFmtIndex)716 void ScExternalRefCache::setCellData(sal_uInt16 nFileId, const String& rTabName, SCCOL nCol, SCROW nRow,
717 TokenRef pToken, sal_uInt32 nFmtIndex)
718 {
719 if (!isDocInitialized(nFileId))
720 return;
721
722 using ::std::pair;
723 DocItem* pDocItem = getDocItem(nFileId);
724 if (!pDocItem)
725 return;
726
727 DocItem& rDoc = *pDocItem;
728
729 // See if the table by this name already exists.
730 TableNameIndexMap::iterator itrTabName = rDoc.maTableNameIndex.find(
731 ScGlobal::pCharClass->upper(rTabName));
732 if (itrTabName == rDoc.maTableNameIndex.end())
733 // Table not found. Maybe the table name or the file id is wrong ???
734 return;
735
736 TableTypeRef& pTableData = rDoc.maTables[itrTabName->second];
737 if (!pTableData.get())
738 pTableData.reset(new Table);
739
740 pTableData->setCell(nCol, nRow, pToken, nFmtIndex);
741 pTableData->setCachedCell(nCol, nRow);
742 }
743
setCellRangeData(sal_uInt16 nFileId,const ScRange & rRange,const vector<SingleRangeData> & rData,TokenArrayRef pArray)744 void ScExternalRefCache::setCellRangeData(sal_uInt16 nFileId, const ScRange& rRange, const vector<SingleRangeData>& rData,
745 TokenArrayRef pArray)
746 {
747 using ::std::pair;
748 if (rData.empty() || !isDocInitialized(nFileId))
749 // nothing to cache
750 return;
751
752 // First, get the document item for the given file ID.
753 DocItem* pDocItem = getDocItem(nFileId);
754 if (!pDocItem)
755 return;
756
757 DocItem& rDoc = *pDocItem;
758
759 // Now, find the table position of the first table to cache.
760 const String& rFirstTabName = rData.front().maTableName;
761 TableNameIndexMap::iterator itrTabName = rDoc.maTableNameIndex.find(
762 ScGlobal::pCharClass->upper(rFirstTabName));
763 if (itrTabName == rDoc.maTableNameIndex.end())
764 {
765 // table index not found.
766 return;
767 }
768
769 size_t nTabFirstId = itrTabName->second;
770 SCROW nRow1 = rRange.aStart.Row(), nRow2 = rRange.aEnd.Row();
771 SCCOL nCol1 = rRange.aStart.Col(), nCol2 = rRange.aEnd.Col();
772 vector<SingleRangeData>::const_iterator itrDataBeg = rData.begin(), itrDataEnd = rData.end();
773 for (vector<SingleRangeData>::const_iterator itrData = itrDataBeg; itrData != itrDataEnd; ++itrData)
774 {
775 size_t i = nTabFirstId + ::std::distance(itrDataBeg, itrData);
776 TableTypeRef& pTabData = rDoc.maTables[i];
777 if (!pTabData.get())
778 pTabData.reset(new Table);
779
780 for (SCROW nRow = nRow1; nRow <= nRow2; ++nRow)
781 {
782 for (SCCOL nCol = nCol1; nCol <= nCol2; ++nCol)
783 {
784 SCSIZE nC = nCol - nCol1, nR = nRow - nRow1;
785 TokenRef pToken;
786 const ScMatrixRef& pMat = itrData->mpRangeData;
787 if (pMat->IsEmpty(nC, nR))
788 // Don't cache empty cells.
789 continue;
790
791 if (pMat->IsValue(nC, nR))
792 pToken.reset(new formula::FormulaDoubleToken(pMat->GetDouble(nC, nR)));
793 else if (pMat->IsString(nC, nR))
794 pToken.reset(new formula::FormulaStringToken(pMat->GetString(nC, nR)));
795
796 if (pToken)
797 // Don't mark this cell 'cached' here, for better performance.
798 pTabData->setCell(nCol, nRow, pToken, 0, false);
799 }
800 }
801 // Mark the whole range 'cached'.
802 pTabData->setCachedCellRange(nCol1, nRow1, nCol2, nRow2);
803 }
804
805 size_t nTabLastId = nTabFirstId + rRange.aEnd.Tab() - rRange.aStart.Tab();
806 ScRange aCacheRange( nCol1, nRow1, static_cast<SCTAB>(nTabFirstId), nCol2, nRow2, static_cast<SCTAB>(nTabLastId));
807
808 rDoc.maRangeArrays.insert( RangeArrayMap::value_type( aCacheRange, pArray));
809 }
810
isDocInitialized(sal_uInt16 nFileId)811 bool ScExternalRefCache::isDocInitialized(sal_uInt16 nFileId)
812 {
813 DocItem* pDoc = getDocItem(nFileId);
814 if (!pDoc)
815 return false;
816
817 return pDoc->mbInitFromSource;
818 }
819
lcl_getTableDataIndex(const ScExternalRefCache::TableNameIndexMap & rMap,const String & rName,size_t & rIndex)820 static bool lcl_getTableDataIndex(const ScExternalRefCache::TableNameIndexMap& rMap, const String& rName, size_t& rIndex)
821 {
822 ScExternalRefCache::TableNameIndexMap::const_iterator itr = rMap.find(rName);
823 if (itr == rMap.end())
824 return false;
825
826 rIndex = itr->second;
827 return true;
828 }
829
initializeDoc(sal_uInt16 nFileId,const vector<String> & rTabNames)830 void ScExternalRefCache::initializeDoc(sal_uInt16 nFileId, const vector<String>& rTabNames)
831 {
832 DocItem* pDoc = getDocItem(nFileId);
833 if (!pDoc)
834 return;
835
836 size_t n = rTabNames.size();
837
838 // table name list - the list must include all table names in the source
839 // document and only to be populated when loading the source document, not
840 // when loading cached data from, say, Excel XCT/CRN records.
841 vector<TableName> aNewTabNames;
842 aNewTabNames.reserve(n);
843 for (vector<String>::const_iterator itr = rTabNames.begin(), itrEnd = rTabNames.end();
844 itr != itrEnd; ++itr)
845 {
846 TableName aNameItem(ScGlobal::pCharClass->upper(*itr), *itr);
847 aNewTabNames.push_back(aNameItem);
848 }
849 pDoc->maTableNames.swap(aNewTabNames);
850
851 // data tables - preserve any existing data that may have been set during
852 // file import.
853 vector<TableTypeRef> aNewTables(n);
854 for (size_t i = 0; i < n; ++i)
855 {
856 size_t nIndex;
857 if (lcl_getTableDataIndex(pDoc->maTableNameIndex, pDoc->maTableNames[i].maUpperName, nIndex))
858 {
859 aNewTables[i] = pDoc->maTables[nIndex];
860 }
861 }
862 pDoc->maTables.swap(aNewTables);
863
864 // name index map
865 TableNameIndexMap aNewNameIndex;
866 for (size_t i = 0; i < n; ++i)
867 aNewNameIndex.insert(TableNameIndexMap::value_type(pDoc->maTableNames[i].maUpperName, i));
868 pDoc->maTableNameIndex.swap(aNewNameIndex);
869
870 pDoc->mbInitFromSource = true;
871 }
872
getTableName(sal_uInt16 nFileId,size_t nCacheId) const873 String ScExternalRefCache::getTableName(sal_uInt16 nFileId, size_t nCacheId) const
874 {
875 if( DocItem* pDoc = getDocItem( nFileId ) )
876 if( nCacheId < pDoc->maTableNames.size() )
877 return pDoc->maTableNames[ nCacheId ].maRealName;
878 return EMPTY_STRING;
879 }
880
getAllTableNames(sal_uInt16 nFileId,vector<String> & rTabNames) const881 void ScExternalRefCache::getAllTableNames(sal_uInt16 nFileId, vector<String>& rTabNames) const
882 {
883 rTabNames.clear();
884 DocItem* pDoc = getDocItem(nFileId);
885 if (!pDoc)
886 return;
887
888 size_t n = pDoc->maTableNames.size();
889 rTabNames.reserve(n);
890 for (vector<TableName>::const_iterator itr = pDoc->maTableNames.begin(), itrEnd = pDoc->maTableNames.end();
891 itr != itrEnd; ++itr)
892 rTabNames.push_back(itr->maRealName);
893 }
894
getTabSpan(sal_uInt16 nFileId,const String & rStartTabName,const String & rEndTabName) const895 SCsTAB ScExternalRefCache::getTabSpan( sal_uInt16 nFileId, const String& rStartTabName, const String& rEndTabName ) const
896 {
897 DocItem* pDoc = getDocItem(nFileId);
898 if (!pDoc)
899 return -1;
900
901 vector<TableName>::const_iterator itrBeg = pDoc->maTableNames.begin();
902 vector<TableName>::const_iterator itrEnd = pDoc->maTableNames.end();
903
904 vector<TableName>::const_iterator itrStartTab = ::std::find_if( itrBeg, itrEnd,
905 TabNameSearchPredicate( rStartTabName));
906 if (itrStartTab == itrEnd)
907 return -1;
908
909 vector<TableName>::const_iterator itrEndTab = ::std::find_if( itrBeg, itrEnd,
910 TabNameSearchPredicate( rEndTabName));
911 if (itrEndTab == itrEnd)
912 return 0;
913
914 size_t nStartDist = ::std::distance( itrBeg, itrStartTab);
915 size_t nEndDist = ::std::distance( itrBeg, itrEndTab);
916 return nStartDist <= nEndDist ? static_cast<SCsTAB>(nEndDist - nStartDist + 1) : -static_cast<SCsTAB>(nStartDist - nEndDist + 1);
917 }
918
getAllNumberFormats(vector<sal_uInt32> & rNumFmts) const919 void ScExternalRefCache::getAllNumberFormats(vector<sal_uInt32>& rNumFmts) const
920 {
921 using ::std::sort;
922 using ::std::unique;
923
924 vector<sal_uInt32> aNumFmts;
925 for (DocDataType::const_iterator itrDoc = maDocs.begin(), itrDocEnd = maDocs.end();
926 itrDoc != itrDocEnd; ++itrDoc)
927 {
928 const vector<TableTypeRef>& rTables = itrDoc->second.maTables;
929 for (vector<TableTypeRef>::const_iterator itrTab = rTables.begin(), itrTabEnd = rTables.end();
930 itrTab != itrTabEnd; ++itrTab)
931 {
932 TableTypeRef pTab = *itrTab;
933 if (!pTab)
934 continue;
935
936 pTab->getAllNumberFormats(aNumFmts);
937 }
938 }
939
940 // remove duplicates.
941 sort(aNumFmts.begin(), aNumFmts.end());
942 aNumFmts.erase(unique(aNumFmts.begin(), aNumFmts.end()), aNumFmts.end());
943 rNumFmts.swap(aNumFmts);
944 }
945
setCacheDocReferenced(sal_uInt16 nFileId)946 bool ScExternalRefCache::setCacheDocReferenced( sal_uInt16 nFileId )
947 {
948 DocItem* pDocItem = getDocItem(nFileId);
949 if (!pDocItem)
950 return areAllCacheTablesReferenced();
951
952 for (::std::vector<TableTypeRef>::iterator itrTab = pDocItem->maTables.begin();
953 itrTab != pDocItem->maTables.end(); ++itrTab)
954 {
955 if ((*itrTab).get())
956 (*itrTab)->setReferenced( true);
957 }
958 addCacheDocToReferenced( nFileId);
959 return areAllCacheTablesReferenced();
960 }
961
setCacheTableReferenced(sal_uInt16 nFileId,const String & rTabName,size_t nSheets,bool bPermanent)962 bool ScExternalRefCache::setCacheTableReferenced( sal_uInt16 nFileId, const String& rTabName, size_t nSheets, bool bPermanent )
963 {
964 DocItem* pDoc = getDocItem(nFileId);
965 if (pDoc)
966 {
967 size_t nIndex = 0;
968 String aTabNameUpper = ScGlobal::pCharClass->upper( rTabName);
969 if (lcl_getTableDataIndex( pDoc->maTableNameIndex, aTabNameUpper, nIndex))
970 {
971 size_t nStop = ::std::min( nIndex + nSheets, pDoc->maTables.size());
972 for (size_t i = nIndex; i < nStop; ++i)
973 {
974 TableTypeRef pTab = pDoc->maTables[i];
975 if (pTab.get())
976 {
977 Table::ReferencedFlag eNewFlag = (bPermanent ?
978 Table::REFERENCED_PERMANENT :
979 Table::REFERENCED_MARKED);
980 Table::ReferencedFlag eOldFlag = pTab->getReferencedFlag();
981 if (eOldFlag != Table::REFERENCED_PERMANENT && eNewFlag != eOldFlag)
982 {
983 pTab->setReferencedFlag( eNewFlag);
984 addCacheTableToReferenced( nFileId, i);
985 }
986 }
987 }
988 }
989 }
990 return areAllCacheTablesReferenced();
991 }
992
setCacheTableReferencedPermanently(sal_uInt16 nFileId,const String & rTabName,size_t nSheets)993 void ScExternalRefCache::setCacheTableReferencedPermanently( sal_uInt16 nFileId, const String& rTabName, size_t nSheets )
994 {
995 DocItem* pDoc = getDocItem(nFileId);
996 if (pDoc)
997 {
998 size_t nIndex = 0;
999 String aTabNameUpper = ScGlobal::pCharClass->upper( rTabName);
1000 if (lcl_getTableDataIndex( pDoc->maTableNameIndex, aTabNameUpper, nIndex))
1001 {
1002 size_t nStop = ::std::min( nIndex + nSheets, pDoc->maTables.size());
1003 for (size_t i = nIndex; i < nStop; ++i)
1004 {
1005 TableTypeRef pTab = pDoc->maTables[i];
1006 if (pTab.get())
1007 pTab->setReferencedFlag( Table::REFERENCED_PERMANENT);
1008 }
1009 }
1010 }
1011 }
1012
setAllCacheTableReferencedStati(bool bReferenced)1013 void ScExternalRefCache::setAllCacheTableReferencedStati( bool bReferenced )
1014 {
1015 if (bReferenced)
1016 {
1017 maReferenced.reset(0);
1018 for (DocDataType::iterator itrDoc = maDocs.begin(); itrDoc != maDocs.end(); ++itrDoc)
1019 {
1020 ScExternalRefCache::DocItem& rDocItem = (*itrDoc).second;
1021 for (::std::vector<TableTypeRef>::iterator itrTab = rDocItem.maTables.begin();
1022 itrTab != rDocItem.maTables.end(); ++itrTab)
1023 {
1024 if ((*itrTab).get())
1025 (*itrTab)->setReferenced( true);
1026 }
1027 }
1028 }
1029 else
1030 {
1031 size_t nDocs = 0;
1032 for (DocDataType::const_iterator itrDoc = maDocs.begin(); itrDoc != maDocs.end(); ++itrDoc)
1033 {
1034 if (nDocs <= (*itrDoc).first)
1035 nDocs = (*itrDoc).first + 1;
1036 }
1037 maReferenced.reset( nDocs);
1038
1039 for (DocDataType::iterator itrDoc = maDocs.begin(); itrDoc != maDocs.end(); ++itrDoc)
1040 {
1041 ScExternalRefCache::DocItem& rDocItem = (*itrDoc).second;
1042 sal_uInt16 nFileId = (*itrDoc).first;
1043 size_t nTables = rDocItem.maTables.size();
1044 ReferencedStatus::DocReferenced & rDocReferenced = maReferenced.maDocs[nFileId];
1045 // All referenced => non-existing tables evaluate as completed.
1046 rDocReferenced.maTables.resize( nTables, true);
1047 for (size_t i=0; i < nTables; ++i)
1048 {
1049 TableTypeRef & xTab = rDocItem.maTables[i];
1050 if (xTab.get())
1051 {
1052 if (xTab->getReferencedFlag() == Table::REFERENCED_PERMANENT)
1053 addCacheTableToReferenced( nFileId, i);
1054 else
1055 {
1056 xTab->setReferencedFlag( Table::UNREFERENCED);
1057 rDocReferenced.maTables[i] = false;
1058 rDocReferenced.mbAllTablesReferenced = false;
1059 // An addCacheTableToReferenced() actually may have
1060 // resulted in mbAllReferenced been set. Clear it.
1061 maReferenced.mbAllReferenced = false;
1062 }
1063 }
1064 }
1065 }
1066 }
1067 }
1068
addCacheTableToReferenced(sal_uInt16 nFileId,size_t nIndex)1069 void ScExternalRefCache::addCacheTableToReferenced( sal_uInt16 nFileId, size_t nIndex )
1070 {
1071 if (nFileId >= maReferenced.maDocs.size())
1072 return;
1073
1074 ::std::vector<bool> & rTables = maReferenced.maDocs[nFileId].maTables;
1075 size_t nTables = rTables.size();
1076 if (nIndex >= nTables)
1077 return;
1078
1079 if (!rTables[nIndex])
1080 {
1081 rTables[nIndex] = true;
1082 size_t i = 0;
1083 while (i < nTables && rTables[i])
1084 ++i;
1085 if (i == nTables)
1086 {
1087 maReferenced.maDocs[nFileId].mbAllTablesReferenced = true;
1088 maReferenced.checkAllDocs();
1089 }
1090 }
1091 }
1092
addCacheDocToReferenced(sal_uInt16 nFileId)1093 void ScExternalRefCache::addCacheDocToReferenced( sal_uInt16 nFileId )
1094 {
1095 if (nFileId >= maReferenced.maDocs.size())
1096 return;
1097
1098 if (!maReferenced.maDocs[nFileId].mbAllTablesReferenced)
1099 {
1100 ::std::vector<bool> & rTables = maReferenced.maDocs[nFileId].maTables;
1101 size_t nSize = rTables.size();
1102 for (size_t i=0; i < nSize; ++i)
1103 rTables[i] = true;
1104 maReferenced.maDocs[nFileId].mbAllTablesReferenced = true;
1105 maReferenced.checkAllDocs();
1106 }
1107 }
1108
areAllCacheTablesReferenced() const1109 bool ScExternalRefCache::areAllCacheTablesReferenced() const
1110 {
1111 return maReferenced.mbAllReferenced;
1112 }
1113
ReferencedStatus()1114 ScExternalRefCache::ReferencedStatus::ReferencedStatus() :
1115 mbAllReferenced(false)
1116 {
1117 reset(0);
1118 }
1119
ReferencedStatus(size_t nDocs)1120 ScExternalRefCache::ReferencedStatus::ReferencedStatus( size_t nDocs ) :
1121 mbAllReferenced(false)
1122 {
1123 reset( nDocs);
1124 }
1125
reset(size_t nDocs)1126 void ScExternalRefCache::ReferencedStatus::reset( size_t nDocs )
1127 {
1128 if (nDocs)
1129 {
1130 mbAllReferenced = false;
1131 DocReferencedVec aRefs( nDocs);
1132 maDocs.swap( aRefs);
1133 }
1134 else
1135 {
1136 mbAllReferenced = true;
1137 DocReferencedVec aRefs;
1138 maDocs.swap( aRefs);
1139 }
1140 }
1141
checkAllDocs()1142 void ScExternalRefCache::ReferencedStatus::checkAllDocs()
1143 {
1144 for (DocReferencedVec::const_iterator itr = maDocs.begin(); itr != maDocs.end(); ++itr)
1145 {
1146 if (!(*itr).mbAllTablesReferenced)
1147 return;
1148 }
1149 mbAllReferenced = true;
1150 }
1151
getCacheTable(sal_uInt16 nFileId,size_t nTabIndex) const1152 ScExternalRefCache::TableTypeRef ScExternalRefCache::getCacheTable(sal_uInt16 nFileId, size_t nTabIndex) const
1153 {
1154 DocItem* pDoc = getDocItem(nFileId);
1155 if (!pDoc || nTabIndex >= pDoc->maTables.size())
1156 return TableTypeRef();
1157
1158 return pDoc->maTables[nTabIndex];
1159 }
1160
getCacheTable(sal_uInt16 nFileId,const String & rTabName,bool bCreateNew,size_t * pnIndex)1161 ScExternalRefCache::TableTypeRef ScExternalRefCache::getCacheTable(sal_uInt16 nFileId, const String& rTabName, bool bCreateNew, size_t* pnIndex)
1162 {
1163 // In API, the index is transported as cached sheet ID of type sal_Int32 in
1164 // sheet::SingleReference.Sheet or sheet::ComplexReference.Reference1.Sheet
1165 // in a sheet::FormulaToken, choose a sensible value for N/A. Effectively
1166 // being 0xffffffff
1167 const size_t nNotAvailable = static_cast<size_t>( static_cast<sal_Int32>( -1));
1168
1169 DocItem* pDoc = getDocItem(nFileId);
1170 if (!pDoc)
1171 {
1172 if (pnIndex) *pnIndex = nNotAvailable;
1173 return TableTypeRef();
1174 }
1175
1176 DocItem& rDoc = *pDoc;
1177
1178 size_t nIndex;
1179 String aTabNameUpper = ScGlobal::pCharClass->upper(rTabName);
1180 if (lcl_getTableDataIndex(rDoc.maTableNameIndex, aTabNameUpper, nIndex))
1181 {
1182 // specified table found.
1183 if( pnIndex ) *pnIndex = nIndex;
1184 if (bCreateNew && !rDoc.maTables[nIndex])
1185 rDoc.maTables[nIndex].reset(new Table);
1186
1187 return rDoc.maTables[nIndex];
1188 }
1189
1190 if (!bCreateNew)
1191 {
1192 if (pnIndex) *pnIndex = nNotAvailable;
1193 return TableTypeRef();
1194 }
1195
1196 // Specified table doesn't exist yet. Create one.
1197 nIndex = rDoc.maTables.size();
1198 if( pnIndex ) *pnIndex = nIndex;
1199 TableTypeRef pTab(new Table);
1200 rDoc.maTables.push_back(pTab);
1201 rDoc.maTableNames.push_back(TableName(aTabNameUpper, rTabName));
1202 rDoc.maTableNameIndex.insert(
1203 TableNameIndexMap::value_type(aTabNameUpper, nIndex));
1204 return pTab;
1205 }
1206
clearCache(sal_uInt16 nFileId)1207 void ScExternalRefCache::clearCache(sal_uInt16 nFileId)
1208 {
1209 maDocs.erase(nFileId);
1210 }
1211
getDocItem(sal_uInt16 nFileId) const1212 ScExternalRefCache::DocItem* ScExternalRefCache::getDocItem(sal_uInt16 nFileId) const
1213 {
1214 using ::std::pair;
1215 DocDataType::iterator itrDoc = maDocs.find(nFileId);
1216 if (itrDoc == maDocs.end())
1217 {
1218 // specified document is not cached.
1219 pair<DocDataType::iterator, bool> res = maDocs.insert(
1220 DocDataType::value_type(nFileId, DocItem()));
1221
1222 if (!res.second)
1223 // insertion failed.
1224 return NULL;
1225
1226 itrDoc = res.first;
1227 }
1228
1229 return &itrDoc->second;
1230 }
1231
1232 // ============================================================================
1233
ScExternalRefLink(ScDocument * pDoc,sal_uInt16 nFileId,const String & rFilter)1234 ScExternalRefLink::ScExternalRefLink(ScDocument* pDoc, sal_uInt16 nFileId, const String& rFilter) :
1235 ::sfx2::SvBaseLink(::sfx2::LINKUPDATE_ONCALL, FORMAT_FILE),
1236 mnFileId(nFileId),
1237 maFilterName(rFilter),
1238 mpDoc(pDoc),
1239 mbDoRefresh(true)
1240 {
1241 }
1242
~ScExternalRefLink()1243 ScExternalRefLink::~ScExternalRefLink()
1244 {
1245 }
1246
Closed()1247 void ScExternalRefLink::Closed()
1248 {
1249 ScExternalRefManager* pMgr = mpDoc->GetExternalRefManager();
1250 pMgr->breakLink(mnFileId);
1251 }
1252
DataChanged(const String &,const Any &)1253 void ScExternalRefLink::DataChanged(const String& /*rMimeType*/, const Any& /*rValue*/)
1254 {
1255 if (!mbDoRefresh)
1256 return;
1257
1258 String aFile, aFilter;
1259 mpDoc->GetLinkManager()->GetDisplayNames(this, NULL, &aFile, NULL, &aFilter);
1260 ScExternalRefManager* pMgr = mpDoc->GetExternalRefManager();
1261 const String* pCurFile = pMgr->getExternalFileName(mnFileId);
1262 if (!pCurFile)
1263 return;
1264
1265 if (pCurFile->Equals(aFile))
1266 {
1267 // Refresh the current source document.
1268 pMgr->refreshNames(mnFileId);
1269 }
1270 else
1271 {
1272 // The source document has changed.
1273 ScDocShell* pDocShell = ScDocShell::GetViewData()->GetDocShell();
1274 ScDocShellModificator aMod(*pDocShell);
1275 pMgr->switchSrcFile(mnFileId, aFile, aFilter);
1276 maFilterName = aFilter;
1277 aMod.SetDocumentModified();
1278 }
1279 }
1280
Edit(Window * pParent,const Link &)1281 void ScExternalRefLink::Edit(Window* pParent, const Link& /*rEndEditHdl*/)
1282 {
1283 SvBaseLink::Edit(pParent, LINK(this, ScExternalRefLink, ExternalRefEndEditHdl));
1284 }
1285
SetDoReferesh(bool b)1286 void ScExternalRefLink::SetDoReferesh(bool b)
1287 {
1288 mbDoRefresh = b;
1289 }
1290
IMPL_LINK(ScExternalRefLink,ExternalRefEndEditHdl,::sfx2::SvBaseLink *,EMPTYARG)1291 IMPL_LINK( ScExternalRefLink, ExternalRefEndEditHdl, ::sfx2::SvBaseLink*, EMPTYARG )
1292 {
1293 return 0;
1294 }
1295
1296 // ============================================================================
1297
lcl_convertToToken(ScBaseCell * pCell)1298 static FormulaToken* lcl_convertToToken(ScBaseCell* pCell)
1299 {
1300 if (!pCell || pCell->HasEmptyData())
1301 {
1302 bool bInherited = (pCell && pCell->GetCellType() == CELLTYPE_FORMULA);
1303 return new ScEmptyCellToken( bInherited, false);
1304 }
1305
1306 switch (pCell->GetCellType())
1307 {
1308 case CELLTYPE_EDIT:
1309 {
1310 String aStr;
1311 static_cast<ScEditCell*>(pCell)->GetString(aStr);
1312 return new formula::FormulaStringToken(aStr);
1313 }
1314 //break;
1315 case CELLTYPE_STRING:
1316 {
1317 String aStr;
1318 static_cast<ScStringCell*>(pCell)->GetString(aStr);
1319 return new formula::FormulaStringToken(aStr);
1320 }
1321 //break;
1322 case CELLTYPE_VALUE:
1323 {
1324 double fVal = static_cast<ScValueCell*>(pCell)->GetValue();
1325 return new formula::FormulaDoubleToken(fVal);
1326 }
1327 //break;
1328 case CELLTYPE_FORMULA:
1329 {
1330 ScFormulaCell* pFCell = static_cast<ScFormulaCell*>(pCell);
1331 sal_uInt16 nError = pFCell->GetErrCode();
1332 if (nError)
1333 return new FormulaErrorToken( nError);
1334 else if (pFCell->IsValue())
1335 {
1336 double fVal = pFCell->GetValue();
1337 return new formula::FormulaDoubleToken(fVal);
1338 }
1339 else
1340 {
1341 String aStr;
1342 pFCell->GetString(aStr);
1343 return new formula::FormulaStringToken(aStr);
1344 }
1345 }
1346 //break;
1347 default:
1348 DBG_ERROR("attempted to convert an unknown cell type.");
1349 }
1350
1351 return NULL;
1352 }
1353
lcl_convertToTokenArray(ScDocument * pSrcDoc,ScRange & rRange,vector<ScExternalRefCache::SingleRangeData> & rCacheData)1354 static ScTokenArray* lcl_convertToTokenArray(ScDocument* pSrcDoc, ScRange& rRange,
1355 vector<ScExternalRefCache::SingleRangeData>& rCacheData)
1356 {
1357 ScAddress& s = rRange.aStart;
1358 ScAddress& e = rRange.aEnd;
1359
1360 SCTAB nTab1 = s.Tab(), nTab2 = e.Tab();
1361 SCCOL nCol1 = s.Col(), nCol2 = e.Col();
1362 SCROW nRow1 = s.Row(), nRow2 = e.Row();
1363
1364 if (nTab2 != nTab1)
1365 // For now, we don't support multi-sheet ranges intentionally because
1366 // we don't have a way to express them in a single token. In the
1367 // future we can introduce a new stack variable type svMatrixList with
1368 // a new token type that can store a 3D matrix value and convert a 3D
1369 // range to it.
1370 return NULL;
1371
1372 ::boost::scoped_ptr<ScRange> pUsedRange;
1373
1374 unique_ptr<ScTokenArray> pArray(new ScTokenArray);
1375 bool bFirstTab = true;
1376 vector<ScExternalRefCache::SingleRangeData>::iterator
1377 itrCache = rCacheData.begin(), itrCacheEnd = rCacheData.end();
1378
1379 for (SCTAB nTab = nTab1; nTab <= nTab2 && itrCache != itrCacheEnd; ++nTab, ++itrCache)
1380 {
1381 // Only loop within the data area.
1382 SCCOL nDataCol1 = nCol1, nDataCol2 = nCol2;
1383 SCROW nDataRow1 = nRow1, nDataRow2 = nRow2;
1384 // the matrix for shrunken data range gives invalid match until the matrix supports the gap
1385 //bool bShrunk;
1386 //if (!pSrcDoc->ShrinkToUsedDataArea( bShrunk, nTab, nDataCol1, nDataRow1, nDataCol2, nDataRow2, false))
1387 // no data within specified range.
1388 // continue;
1389
1390 if (pUsedRange.get())
1391 // Make sure the used area only grows, not shrinks.
1392 pUsedRange->ExtendTo(ScRange(nDataCol1, nDataRow1, 0, nDataCol2, nDataRow2, 0));
1393 else
1394 pUsedRange.reset(new ScRange(nDataCol1, nDataRow1, 0, nDataCol2, nDataRow2, 0));
1395
1396 ScMatrixRef xMat = new ScMatrix(
1397 static_cast<SCSIZE>(nDataCol2-nDataCol1+1),
1398 static_cast<SCSIZE>(nDataRow2-nDataRow1+1));
1399
1400 for (SCCOL nCol = nDataCol1; nCol <= nDataCol2; ++nCol)
1401 {
1402 for (SCROW nRow = nDataRow1; nRow <= nDataRow2; ++nRow)
1403 {
1404 SCSIZE nC = nCol - nCol1, nR = nRow - nRow1;
1405 ScBaseCell* pCell;
1406 pSrcDoc->GetCell(nCol, nRow, nTab, pCell);
1407 if (!pCell || pCell->HasEmptyData())
1408 xMat->PutEmpty(nC, nR);
1409 else
1410 {
1411 switch (pCell->GetCellType())
1412 {
1413 case CELLTYPE_EDIT:
1414 {
1415 String aStr;
1416 static_cast<ScEditCell*>(pCell)->GetString(aStr);
1417 xMat->PutString(aStr, nC, nR);
1418 }
1419 break;
1420 case CELLTYPE_STRING:
1421 {
1422 String aStr;
1423 static_cast<ScStringCell*>(pCell)->GetString(aStr);
1424 xMat->PutString(aStr, nC, nR);
1425 }
1426 break;
1427 case CELLTYPE_VALUE:
1428 {
1429 double fVal = static_cast<ScValueCell*>(pCell)->GetValue();
1430 xMat->PutDouble(fVal, nC, nR);
1431 }
1432 break;
1433 case CELLTYPE_FORMULA:
1434 {
1435 ScFormulaCell* pFCell = static_cast<ScFormulaCell*>(pCell);
1436 sal_uInt16 nError = pFCell->GetErrCode();
1437 if (nError)
1438 xMat->PutDouble( CreateDoubleError( nError), nC, nR);
1439 else if (pFCell->IsValue())
1440 {
1441 double fVal = pFCell->GetValue();
1442 xMat->PutDouble(fVal, nC, nR);
1443 }
1444 else
1445 {
1446 String aStr;
1447 pFCell->GetString(aStr);
1448 xMat->PutString(aStr, nC, nR);
1449 }
1450 }
1451 break;
1452 default:
1453 DBG_ERROR("attempted to convert an unknown cell type.");
1454 }
1455 }
1456 }
1457 }
1458 if (!bFirstTab)
1459 pArray->AddOpCode(ocSep);
1460
1461 ScMatrix* pMat2 = xMat;
1462 ScMatrixToken aToken(pMat2);
1463 pArray->AddToken(aToken);
1464
1465 itrCache->mpRangeData = xMat;
1466
1467 bFirstTab = false;
1468 }
1469
1470 if (!pUsedRange.get())
1471 return NULL;
1472
1473 s.SetCol(pUsedRange->aStart.Col());
1474 s.SetRow(pUsedRange->aStart.Row());
1475 e.SetCol(pUsedRange->aEnd.Col());
1476 e.SetRow(pUsedRange->aEnd.Row());
1477
1478 return pArray.release();
1479 }
1480
lcl_fillEmptyMatrix(const ScRange & rRange)1481 static ScTokenArray* lcl_fillEmptyMatrix(const ScRange& rRange)
1482 {
1483 SCSIZE nC = static_cast<SCSIZE>(rRange.aEnd.Col()-rRange.aStart.Col()+1);
1484 SCSIZE nR = static_cast<SCSIZE>(rRange.aEnd.Row()-rRange.aStart.Row()+1);
1485 ScMatrixRef xMat = new ScMatrix(nC, nR);
1486 for (SCSIZE i = 0; i < nC; ++i)
1487 for (SCSIZE j = 0; j < nR; ++j)
1488 xMat->PutEmpty(i, j);
1489
1490 ScMatrix* pMat2 = xMat;
1491 ScMatrixToken aToken(pMat2);
1492 unique_ptr<ScTokenArray> pArray(new ScTokenArray);
1493 pArray->AddToken(aToken);
1494 return pArray.release();
1495 }
1496
ScExternalRefManager(ScDocument * pDoc)1497 ScExternalRefManager::ScExternalRefManager(ScDocument* pDoc) :
1498 mpDoc(pDoc),
1499 mbInReferenceMarking(false),
1500 mbUserInteractionEnabled(true)
1501 {
1502 maSrcDocTimer.SetTimeoutHdl( LINK(this, ScExternalRefManager, TimeOutHdl) );
1503 maSrcDocTimer.SetTimeout(SRCDOC_SCAN_INTERVAL);
1504 }
1505
~ScExternalRefManager()1506 ScExternalRefManager::~ScExternalRefManager()
1507 {
1508 clear();
1509 }
1510
getCacheTableName(sal_uInt16 nFileId,size_t nTabIndex) const1511 String ScExternalRefManager::getCacheTableName(sal_uInt16 nFileId, size_t nTabIndex) const
1512 {
1513 return maRefCache.getTableName(nFileId, nTabIndex);
1514 }
1515
getCacheTable(sal_uInt16 nFileId,size_t nTabIndex) const1516 ScExternalRefCache::TableTypeRef ScExternalRefManager::getCacheTable(sal_uInt16 nFileId, size_t nTabIndex) const
1517 {
1518 return maRefCache.getCacheTable(nFileId, nTabIndex);
1519 }
1520
getCacheTable(sal_uInt16 nFileId,const String & rTabName,bool bCreateNew,size_t * pnIndex)1521 ScExternalRefCache::TableTypeRef ScExternalRefManager::getCacheTable(sal_uInt16 nFileId, const String& rTabName, bool bCreateNew, size_t* pnIndex)
1522 {
1523 return maRefCache.getCacheTable(nFileId, rTabName, bCreateNew, pnIndex);
1524 }
1525
1526 // ============================================================================
1527
LinkListener()1528 ScExternalRefManager::LinkListener::LinkListener()
1529 {
1530 }
1531
~LinkListener()1532 ScExternalRefManager::LinkListener::~LinkListener()
1533 {
1534 }
1535
1536 // ----------------------------------------------------------------------------
1537
ApiGuard(ScDocument * pDoc)1538 ScExternalRefManager::ApiGuard::ApiGuard(ScDocument* pDoc) :
1539 mpMgr(pDoc->GetExternalRefManager()),
1540 mbOldInteractionEnabled(mpMgr->mbUserInteractionEnabled)
1541 {
1542 // We don't want user interaction handled in the API.
1543 mpMgr->mbUserInteractionEnabled = false;
1544 }
1545
~ApiGuard()1546 ScExternalRefManager::ApiGuard::~ApiGuard()
1547 {
1548 // Restore old value.
1549 mpMgr->mbUserInteractionEnabled = mbOldInteractionEnabled;
1550 }
1551
1552 // ----------------------------------------------------------------------------
1553
getAllCachedTableNames(sal_uInt16 nFileId,vector<String> & rTabNames) const1554 void ScExternalRefManager::getAllCachedTableNames(sal_uInt16 nFileId, vector<String>& rTabNames) const
1555 {
1556 maRefCache.getAllTableNames(nFileId, rTabNames);
1557 }
1558
getCachedTabSpan(sal_uInt16 nFileId,const String & rStartTabName,const String & rEndTabName) const1559 SCsTAB ScExternalRefManager::getCachedTabSpan( sal_uInt16 nFileId, const String& rStartTabName, const String& rEndTabName ) const
1560 {
1561 return maRefCache.getTabSpan( nFileId, rStartTabName, rEndTabName);
1562 }
1563
getAllCachedNumberFormats(vector<sal_uInt32> & rNumFmts) const1564 void ScExternalRefManager::getAllCachedNumberFormats(vector<sal_uInt32>& rNumFmts) const
1565 {
1566 maRefCache.getAllNumberFormats(rNumFmts);
1567 }
1568
getExternalFileCount() const1569 sal_uInt16 ScExternalRefManager::getExternalFileCount() const
1570 {
1571 return static_cast< sal_uInt16 >( maSrcFiles.size() );
1572 }
1573
markUsedByLinkListeners()1574 bool ScExternalRefManager::markUsedByLinkListeners()
1575 {
1576 bool bAllMarked = false;
1577 for (LinkListenerMap::const_iterator itr = maLinkListeners.begin();
1578 itr != maLinkListeners.end() && !bAllMarked; ++itr)
1579 {
1580 if (!(*itr).second.empty())
1581 bAllMarked = maRefCache.setCacheDocReferenced( (*itr).first);
1582 /* TODO: LinkListeners should remember the table they're listening to.
1583 * As is, listening to one table will mark all tables of the document
1584 * being referenced. */
1585 }
1586 return bAllMarked;
1587 }
1588
markUsedExternalRefCells()1589 bool ScExternalRefManager::markUsedExternalRefCells()
1590 {
1591 RefCellMap::iterator itr = maRefCells.begin(), itrEnd = maRefCells.end();
1592 for (; itr != itrEnd; ++itr)
1593 {
1594 RefCellSet::iterator itrCell = itr->second.begin(), itrCellEnd = itr->second.end();
1595 for (; itrCell != itrCellEnd; ++itrCell)
1596 {
1597 ScFormulaCell* pCell = *itrCell;
1598 bool bUsed = pCell->MarkUsedExternalReferences();
1599 if (bUsed)
1600 // Return true when at least one cell references external docs.
1601 return true;
1602 }
1603 }
1604 return false;
1605 }
1606
setCacheTableReferenced(sal_uInt16 nFileId,const String & rTabName,size_t nSheets)1607 bool ScExternalRefManager::setCacheTableReferenced( sal_uInt16 nFileId, const String& rTabName, size_t nSheets )
1608 {
1609 return maRefCache.setCacheTableReferenced( nFileId, rTabName, nSheets, false);
1610 }
1611
setCacheTableReferencedPermanently(sal_uInt16 nFileId,const String & rTabName,size_t nSheets)1612 void ScExternalRefManager::setCacheTableReferencedPermanently( sal_uInt16 nFileId, const String& rTabName, size_t nSheets )
1613 {
1614 if (isInReferenceMarking())
1615 // Do all maintenance work.
1616 maRefCache.setCacheTableReferenced( nFileId, rTabName, nSheets, true);
1617 else
1618 // Set only the permanent flag.
1619 maRefCache.setCacheTableReferencedPermanently( nFileId, rTabName, nSheets);
1620 }
1621
setAllCacheTableReferencedStati(bool bReferenced)1622 void ScExternalRefManager::setAllCacheTableReferencedStati( bool bReferenced )
1623 {
1624 mbInReferenceMarking = !bReferenced;
1625 maRefCache.setAllCacheTableReferencedStati( bReferenced );
1626 }
1627
storeRangeNameTokens(sal_uInt16 nFileId,const String & rName,const ScTokenArray & rArray)1628 void ScExternalRefManager::storeRangeNameTokens(sal_uInt16 nFileId, const String& rName, const ScTokenArray& rArray)
1629 {
1630 ScExternalRefCache::TokenArrayRef pArray(rArray.Clone());
1631 maRefCache.setRangeNameTokens(nFileId, rName, pArray);
1632 }
1633
getSingleRefToken(sal_uInt16 nFileId,const String & rTabName,const ScAddress & rCell,const ScAddress * pCurPos,SCTAB * pTab,ScExternalRefCache::CellFormat * pFmt)1634 ScExternalRefCache::TokenRef ScExternalRefManager::getSingleRefToken(
1635 sal_uInt16 nFileId, const String& rTabName, const ScAddress& rCell,
1636 const ScAddress* pCurPos, SCTAB* pTab, ScExternalRefCache::CellFormat* pFmt)
1637 {
1638 if (pCurPos)
1639 insertRefCell(nFileId, *pCurPos);
1640
1641 maybeLinkExternalFile(nFileId);
1642
1643 if (pTab)
1644 *pTab = -1;
1645
1646 if (pFmt)
1647 pFmt->mbIsSet = false;
1648
1649 // Check if the given table name and the cell position is cached.
1650 sal_uInt32 nFmtIndex = 0;
1651 ScExternalRefCache::TokenRef pToken = maRefCache.getCellData(
1652 nFileId, rTabName, rCell.Col(), rCell.Row(), &nFmtIndex);
1653 if (pToken)
1654 {
1655 // Cache hit !
1656 if (pFmt)
1657 {
1658 short nFmtType = mpDoc->GetFormatTable()->GetType(nFmtIndex);
1659 if (nFmtType != NUMBERFORMAT_UNDEFINED)
1660 {
1661 pFmt->mbIsSet = true;
1662 pFmt->mnIndex = nFmtIndex;
1663 pFmt->mnType = nFmtType;
1664 }
1665 }
1666 return pToken;
1667 }
1668
1669 // reference not cached. read from the source document.
1670 ScDocument* pSrcDoc = getSrcDocument(nFileId);
1671 if (!pSrcDoc)
1672 {
1673 // Source document not reachable. Throw a reference error.
1674 pToken.reset(new FormulaErrorToken(errNoRef));
1675 return pToken;
1676 }
1677
1678 ScBaseCell* pCell = NULL;
1679 SCTAB nTab;
1680 if (!pSrcDoc->GetTable(rTabName, nTab))
1681 {
1682 // specified table name doesn't exist in the source document.
1683 pToken.reset(new FormulaErrorToken(errNoRef));
1684 return pToken;
1685 }
1686
1687 if (pTab)
1688 *pTab = nTab;
1689
1690 SCCOL nDataCol1 = 0, nDataCol2 = MAXCOL;
1691 SCROW nDataRow1 = 0, nDataRow2 = MAXROW;
1692 bool bData = pSrcDoc->ShrinkToDataArea(nTab, nDataCol1, nDataRow1, nDataCol2, nDataRow2);
1693 if (!bData || rCell.Col() < nDataCol1 || nDataCol2 < rCell.Col() || rCell.Row() < nDataRow1 || nDataRow2 < rCell.Row())
1694 {
1695 // requested cell is outside the data area. Don't even bother caching
1696 // this data, but add it to the cached range to prevent accessing the
1697 // source document time and time again.
1698 ScExternalRefCache::TableTypeRef pCacheTab =
1699 maRefCache.getCacheTable(nFileId, rTabName, true, NULL);
1700 if (pCacheTab)
1701 pCacheTab->setCachedCell(rCell.Col(), rCell.Row());
1702
1703 pToken.reset(new ScEmptyCellToken(false, false));
1704 return pToken;
1705 }
1706
1707 pSrcDoc->GetCell(rCell.Col(), rCell.Row(), nTab, pCell);
1708 ScExternalRefCache::TokenRef pTok(lcl_convertToToken(pCell));
1709
1710 pSrcDoc->GetNumberFormat(rCell.Col(), rCell.Row(), nTab, nFmtIndex);
1711 nFmtIndex = getMappedNumberFormat(nFileId, nFmtIndex, pSrcDoc);
1712 if (pFmt)
1713 {
1714 short nFmtType = mpDoc->GetFormatTable()->GetType(nFmtIndex);
1715 if (nFmtType != NUMBERFORMAT_UNDEFINED)
1716 {
1717 pFmt->mbIsSet = true;
1718 pFmt->mnIndex = nFmtIndex;
1719 pFmt->mnType = nFmtType;
1720 }
1721 }
1722
1723 if (!pTok.get())
1724 {
1725 // Generate an error for unresolvable cells.
1726 pTok.reset( new FormulaErrorToken( errNoValue));
1727 }
1728
1729 // Now, insert the token into cache table but don't cache empty cells.
1730 if (pTok->GetType() != formula::svEmptyCell)
1731 maRefCache.setCellData(nFileId, rTabName, rCell.Col(), rCell.Row(), pTok, nFmtIndex);
1732
1733 return pTok;
1734 }
1735
getDoubleRefTokens(sal_uInt16 nFileId,const String & rTabName,const ScRange & rRange,const ScAddress * pCurPos)1736 ScExternalRefCache::TokenArrayRef ScExternalRefManager::getDoubleRefTokens(
1737 sal_uInt16 nFileId, const String& rTabName, const ScRange& rRange, const ScAddress* pCurPos)
1738 {
1739 if (pCurPos)
1740 insertRefCell(nFileId, *pCurPos);
1741
1742 maybeLinkExternalFile(nFileId);
1743
1744 // Check if the given table name and the cell position is cached.
1745 ScExternalRefCache::TokenArrayRef pArray =
1746 maRefCache.getCellRangeData(nFileId, rTabName, rRange);
1747 if (pArray)
1748 // Cache hit !
1749 return pArray;
1750
1751 ScDocument* pSrcDoc = getSrcDocument(nFileId);
1752 if (!pSrcDoc)
1753 {
1754 // Source document is not reachable. Throw a reference error.
1755 pArray.reset(new ScTokenArray);
1756 pArray->AddToken(FormulaErrorToken(errNoRef));
1757 return pArray;
1758 }
1759
1760 SCTAB nTab1;
1761 if (!pSrcDoc->GetTable(rTabName, nTab1))
1762 {
1763 // specified table name doesn't exist in the source document.
1764 pArray.reset(new ScTokenArray);
1765 pArray->AddToken(FormulaErrorToken(errNoRef));
1766 return pArray;
1767 }
1768
1769 ScRange aRange(rRange);
1770 SCTAB nTabSpan = aRange.aEnd.Tab() - aRange.aStart.Tab();
1771
1772 vector<ScExternalRefCache::SingleRangeData> aCacheData;
1773 aCacheData.reserve(nTabSpan+1);
1774 aCacheData.push_back(ScExternalRefCache::SingleRangeData());
1775 aCacheData.back().maTableName = ScGlobal::pCharClass->upper(rTabName);
1776
1777 for (SCTAB i = 1; i < nTabSpan + 1; ++i)
1778 {
1779 String aTabName;
1780 if (!pSrcDoc->GetName(nTab1 + 1, aTabName))
1781 // source document doesn't have any table by the specified name.
1782 break;
1783
1784 aCacheData.push_back(ScExternalRefCache::SingleRangeData());
1785 aCacheData.back().maTableName = ScGlobal::pCharClass->upper(aTabName);
1786 }
1787
1788 aRange.aStart.SetTab(nTab1);
1789 aRange.aEnd.SetTab(nTab1 + nTabSpan);
1790
1791 pArray.reset(lcl_convertToTokenArray(pSrcDoc, aRange, aCacheData));
1792
1793 if (pArray)
1794 // Cache these values.
1795 maRefCache.setCellRangeData(nFileId, aRange, aCacheData, pArray);
1796 else
1797 {
1798 // Array is empty. Fill it with an empty matrix of the required size.
1799 pArray.reset(lcl_fillEmptyMatrix(rRange));
1800
1801 // Make sure to set this range 'cached', to prevent unnecessarily
1802 // accessing the src document time and time again.
1803 ScExternalRefCache::TableTypeRef pCacheTab =
1804 maRefCache.getCacheTable(nFileId, rTabName, true, NULL);
1805 if (pCacheTab)
1806 pCacheTab->setCachedCellRange(
1807 rRange.aStart.Col(), rRange.aStart.Row(), rRange.aEnd.Col(), rRange.aEnd.Row());
1808 }
1809
1810 return pArray;
1811 }
1812
getRangeNameTokens(sal_uInt16 nFileId,const String & rName,const ScAddress * pCurPos)1813 ScExternalRefCache::TokenArrayRef ScExternalRefManager::getRangeNameTokens(sal_uInt16 nFileId, const String& rName, const ScAddress* pCurPos)
1814 {
1815 if (pCurPos)
1816 insertRefCell(nFileId, *pCurPos);
1817
1818 maybeLinkExternalFile(nFileId);
1819
1820 ScExternalRefCache::TokenArrayRef pArray = maRefCache.getRangeNameTokens(nFileId, rName);
1821 if (pArray.get())
1822 return pArray;
1823
1824 ScDocument* pSrcDoc = getSrcDocument(nFileId);
1825 if (!pSrcDoc)
1826 return ScExternalRefCache::TokenArrayRef();
1827
1828 ScRangeName* pExtNames = pSrcDoc->GetRangeName();
1829 String aUpperName = ScGlobal::pCharClass->upper(rName);
1830 sal_uInt16 n;
1831 bool bRes = pExtNames->SearchNameUpper(aUpperName, n);
1832 if (!bRes)
1833 return ScExternalRefCache::TokenArrayRef();
1834
1835 ScRangeData* pRangeData = (*pExtNames)[n];
1836 if (!pRangeData)
1837 return ScExternalRefCache::TokenArrayRef();
1838
1839 // Parse all tokens in this external range data, and replace each absolute
1840 // reference token with an external reference token, and cache them. Also
1841 // register the source document with the link manager if it's a new
1842 // source.
1843
1844 ScExternalRefCache::TokenArrayRef pNew(new ScTokenArray);
1845
1846 ScTokenArray* pCode = pRangeData->GetCode();
1847 for (FormulaToken* pToken = pCode->First(); pToken; pToken = pCode->Next())
1848 {
1849 bool bTokenAdded = false;
1850 switch (pToken->GetType())
1851 {
1852 case svSingleRef:
1853 {
1854 const ScSingleRefData& rRef = static_cast<ScToken*>(pToken)->GetSingleRef();
1855 String aTabName;
1856 pSrcDoc->GetName(rRef.nTab, aTabName);
1857 ScExternalSingleRefToken aNewToken(nFileId, aTabName, static_cast<ScToken*>(pToken)->GetSingleRef());
1858 pNew->AddToken(aNewToken);
1859 bTokenAdded = true;
1860 }
1861 break;
1862 case svDoubleRef:
1863 {
1864 const ScSingleRefData& rRef = static_cast<ScToken*>(pToken)->GetSingleRef();
1865 String aTabName;
1866 pSrcDoc->GetName(rRef.nTab, aTabName);
1867 ScExternalDoubleRefToken aNewToken(nFileId, aTabName, static_cast<ScToken*>(pToken)->GetDoubleRef());
1868 pNew->AddToken(aNewToken);
1869 bTokenAdded = true;
1870 }
1871 break;
1872 default:
1873 ; // nothing
1874 }
1875
1876 if (!bTokenAdded)
1877 pNew->AddToken(*pToken);
1878 }
1879
1880 // Make sure to pass the correctly-cased range name here.
1881 maRefCache.setRangeNameTokens(nFileId, pRangeData->GetName(), pNew);
1882 return pNew;
1883 }
1884
refreshAllRefCells(sal_uInt16 nFileId)1885 void ScExternalRefManager::refreshAllRefCells(sal_uInt16 nFileId)
1886 {
1887 RefCellMap::iterator itrFile = maRefCells.find(nFileId);
1888 if (itrFile == maRefCells.end())
1889 return;
1890
1891 RefCellSet& rRefCells = itrFile->second;
1892 for_each(rRefCells.begin(), rRefCells.end(), UpdateFormulaCell());
1893
1894 ScViewData* pViewData = ScDocShell::GetViewData();
1895 if (!pViewData)
1896 return;
1897
1898 ScTabViewShell* pVShell = pViewData->GetViewShell();
1899 if (!pVShell)
1900 return;
1901
1902 // Repainting the grid also repaints the texts, but is there a better way
1903 // to refresh texts?
1904 pVShell->Invalidate(FID_REPAINT);
1905 pVShell->PaintGrid();
1906 }
1907
insertRefCell(sal_uInt16 nFileId,const ScAddress & rCell)1908 void ScExternalRefManager::insertRefCell(sal_uInt16 nFileId, const ScAddress& rCell)
1909 {
1910 RefCellMap::iterator itr = maRefCells.find(nFileId);
1911 if (itr == maRefCells.end())
1912 {
1913 RefCellSet aRefCells;
1914 pair<RefCellMap::iterator, bool> r = maRefCells.insert(
1915 RefCellMap::value_type(nFileId, aRefCells));
1916 if (!r.second)
1917 // insertion failed.
1918 return;
1919
1920 itr = r.first;
1921 }
1922
1923 ScBaseCell* pCell = mpDoc->GetCell(rCell);
1924 if (pCell && pCell->GetCellType() == CELLTYPE_FORMULA)
1925 itr->second.insert(static_cast<ScFormulaCell*>(pCell));
1926 }
1927
getSrcDocument(sal_uInt16 nFileId)1928 ScDocument* ScExternalRefManager::getSrcDocument(sal_uInt16 nFileId)
1929 {
1930 if (!mpDoc->IsExecuteLinkEnabled())
1931 return NULL;
1932
1933 DocShellMap::iterator itrEnd = maDocShells.end();
1934 DocShellMap::iterator itr = maDocShells.find(nFileId);
1935
1936 if (itr != itrEnd)
1937 {
1938 // document already loaded.
1939
1940 // TODO: Find out a way to access a document that's already open in
1941 // memory and re-use that instance, instead of loading it from the
1942 // disk again.
1943
1944 SfxObjectShell* p = itr->second.maShell;
1945 itr->second.maLastAccess = Time();
1946 return static_cast<ScDocShell*>(p)->GetDocument();
1947 }
1948
1949 const String* pFile = getExternalFileName(nFileId);
1950 if (!pFile)
1951 // no file name associated with this ID.
1952 return NULL;
1953
1954 String aFilter;
1955 SrcShell aSrcDoc;
1956 aSrcDoc.maShell = loadSrcDocument(nFileId, aFilter);
1957 if (!aSrcDoc.maShell.Is())
1958 {
1959 // source document could not be loaded.
1960 return NULL;
1961 }
1962
1963 if (maDocShells.empty())
1964 {
1965 // If this is the first source document insertion, start up the timer.
1966 maSrcDocTimer.Start();
1967 }
1968
1969 maDocShells.insert(DocShellMap::value_type(nFileId, aSrcDoc));
1970 SfxObjectShell* p = aSrcDoc.maShell;
1971 ScDocument* pSrcDoc = static_cast<ScDocShell*>(p)->GetDocument();
1972
1973 SCTAB nTabCount = pSrcDoc->GetTableCount();
1974 if (!maRefCache.isDocInitialized(nFileId) && nTabCount)
1975 {
1976 // Populate the cache with all table names in the source document.
1977 vector<String> aTabNames;
1978 aTabNames.reserve(nTabCount);
1979 for (SCTAB i = 0; i < nTabCount; ++i)
1980 {
1981 String aName;
1982 pSrcDoc->GetName(i, aName);
1983 aTabNames.push_back(aName);
1984 }
1985 maRefCache.initializeDoc(nFileId, aTabNames);
1986 }
1987 return pSrcDoc;
1988 }
1989
loadSrcDocument(sal_uInt16 nFileId,String & rFilter)1990 SfxObjectShellRef ScExternalRefManager::loadSrcDocument(sal_uInt16 nFileId, String& rFilter)
1991 {
1992 const SrcFileData* pFileData = getExternalFileData(nFileId);
1993 if (!pFileData)
1994 return NULL;
1995
1996 // Always load the document by using the path created from the relative
1997 // path. If the referenced document is not there, simply exit. The
1998 // original file name should be used only when the relative path is not
1999 // given.
2000 String aFile = pFileData->maFileName;
2001 maybeCreateRealFileName(nFileId);
2002 if (pFileData->maRealFileName.Len())
2003 aFile = pFileData->maRealFileName;
2004
2005 if (!isFileLoadable(aFile))
2006 return NULL;
2007
2008 String aOptions( pFileData->maFilterOptions );
2009 if ( pFileData->maFilterName.Len() )
2010 rFilter = pFileData->maFilterName; // don't overwrite stored filter with guessed filter
2011 else
2012 ScDocumentLoader::GetFilterName(aFile, rFilter, aOptions, true, false);
2013 const SfxFilter* pFilter = ScDocShell::Factory().GetFilterContainer()->GetFilter4FilterName(rFilter);
2014
2015 if (!pFileData->maRelativeName.Len())
2016 {
2017 // Generate a relative file path.
2018 INetURLObject aBaseURL(getOwnDocumentName());
2019 aBaseURL.insertName(OUString::createFromAscii("content.xml"));
2020
2021 String aStr = URIHelper::simpleNormalizedMakeRelative(
2022 aBaseURL.GetMainURL(INetURLObject::NO_DECODE), aFile);
2023
2024 setRelativeFileName(nFileId, aStr);
2025 }
2026
2027 SfxItemSet* pSet = new SfxAllItemSet(SFX_APP()->GetPool());
2028 if (aOptions.Len())
2029 pSet->Put(SfxStringItem(SID_FILE_FILTEROPTIONS, aOptions));
2030
2031 // make medium hidden to prevent assertion from progress bar
2032 pSet->Put( SfxBoolItem( SID_HIDDEN, sal_True ) );
2033
2034 unique_ptr<SfxMedium> pMedium(new SfxMedium(aFile, STREAM_STD_READ, false, pFilter, pSet));
2035 if (pMedium->GetError() != ERRCODE_NONE)
2036 return NULL;
2037
2038 // To load encrypted documents with password, user interaction needs to be enabled.
2039 pMedium->UseInteractionHandler(mbUserInteractionEnabled);
2040
2041 ScDocShell* pNewShell = new ScDocShell(SFX_CREATE_MODE_INTERNAL);
2042 SfxObjectShellRef aRef = pNewShell;
2043
2044 // increment the recursive link count of the source document.
2045 ScExtDocOptions* pExtOpt = mpDoc->GetExtDocOptions();
2046 sal_uInt32 nLinkCount = pExtOpt ? pExtOpt->GetDocSettings().mnLinkCnt : 0;
2047 ScDocument* pSrcDoc = pNewShell->GetDocument();
2048 pSrcDoc->EnableExecuteLink(false); // to prevent circular access of external references.
2049 pSrcDoc->EnableUndo(false);
2050 pSrcDoc->EnableAdjustHeight(false);
2051
2052 ScExtDocOptions* pExtOptNew = pSrcDoc->GetExtDocOptions();
2053 if (!pExtOptNew)
2054 {
2055 pExtOptNew = new ScExtDocOptions;
2056 pSrcDoc->SetExtDocOptions(pExtOptNew);
2057 }
2058 pExtOptNew->GetDocSettings().mnLinkCnt = nLinkCount + 1;
2059
2060 pNewShell->DoLoad(pMedium.release());
2061
2062 // with UseInteractionHandler, options may be set by dialog during DoLoad
2063 String aNew = ScDocumentLoader::GetOptions(*pNewShell->GetMedium());
2064 if (aNew.Len() && aNew != aOptions)
2065 aOptions = aNew;
2066 setFilterData(nFileId, rFilter, aOptions); // update the filter data, including the new options
2067
2068 return aRef;
2069 }
2070
isFileLoadable(const String & rFile) const2071 bool ScExternalRefManager::isFileLoadable(const String& rFile) const
2072 {
2073 if (!rFile.Len())
2074 return false;
2075
2076 if (isOwnDocument(rFile))
2077 return false;
2078
2079 String aPhysical;
2080 if (utl::LocalFileHelper::ConvertURLToPhysicalName(rFile, aPhysical) && aPhysical.Len())
2081 {
2082 // #i114504# try IsFolder/Exists only for file URLs
2083
2084 if (utl::UCBContentHelper::IsFolder(rFile))
2085 return false;
2086
2087 return utl::UCBContentHelper::Exists(rFile);
2088 }
2089 else
2090 return true; // for http and others, Exists doesn't work, but the URL can still be opened
2091 }
2092
maybeLinkExternalFile(sal_uInt16 nFileId)2093 void ScExternalRefManager::maybeLinkExternalFile(sal_uInt16 nFileId)
2094 {
2095 if (maLinkedDocs.count(nFileId))
2096 // file already linked, or the link has been broken.
2097 return;
2098
2099 // Source document not linked yet. Link it now.
2100 const String* pFileName = getExternalFileName(nFileId);
2101 if (!pFileName)
2102 return;
2103
2104 String aFilter, aOptions;
2105 const SrcFileData* pFileData = getExternalFileData(nFileId);
2106 if (pFileData)
2107 {
2108 aFilter = pFileData->maFilterName;
2109 aOptions = pFileData->maFilterOptions;
2110 }
2111 // If a filter was already set (for example, loading the cached table),
2112 // don't call GetFilterName which has to access the source file.
2113 if (!aFilter.Len())
2114 ScDocumentLoader::GetFilterName(*pFileName, aFilter, aOptions, true, false);
2115 sfx2::LinkManager* pLinkMgr = mpDoc->GetLinkManager();
2116 ScExternalRefLink* pLink = new ScExternalRefLink(mpDoc, nFileId, aFilter);
2117 DBG_ASSERT(pFileName, "ScExternalRefManager::insertExternalFileLink: file name pointer is NULL");
2118 pLinkMgr->InsertFileLink(*pLink, OBJECT_CLIENT_FILE, *pFileName, &aFilter);
2119
2120 pLink->SetDoReferesh(false);
2121 pLink->Update();
2122 pLink->SetDoReferesh(true);
2123
2124 maLinkedDocs.insert(LinkedDocMap::value_type(nFileId, true));
2125 }
2126
maybeCreateRealFileName(const String & rOwnDocName)2127 void ScExternalRefManager::SrcFileData::maybeCreateRealFileName(const String& rOwnDocName)
2128 {
2129 if (!maRelativeName.Len())
2130 // No relative path given. Nothing to do.
2131 return;
2132
2133 if (maRealFileName.Len())
2134 // Real file name already created. Nothing to do.
2135 return;
2136
2137 // Formulate the absolute file path from the relative path.
2138 const String& rRelPath = maRelativeName;
2139 INetURLObject aBaseURL(rOwnDocName);
2140 aBaseURL.insertName(OUString::createFromAscii("content.xml"));
2141 bool bWasAbs = false;
2142 maRealFileName = aBaseURL.smartRel2Abs(rRelPath, bWasAbs).GetMainURL(INetURLObject::NO_DECODE);
2143 }
2144
maybeCreateRealFileName(sal_uInt16 nFileId)2145 void ScExternalRefManager::maybeCreateRealFileName(sal_uInt16 nFileId)
2146 {
2147 if (nFileId >= maSrcFiles.size())
2148 return;
2149
2150 maSrcFiles[nFileId].maybeCreateRealFileName(getOwnDocumentName());
2151 }
2152
getOwnDocumentName() const2153 const String& ScExternalRefManager::getOwnDocumentName() const
2154 {
2155 SfxObjectShell* pShell = mpDoc->GetDocumentShell();
2156 if (!pShell)
2157 // This should not happen!
2158 return EMPTY_STRING;
2159
2160 SfxMedium* pMed = pShell->GetMedium();
2161 if (!pMed)
2162 return EMPTY_STRING;
2163
2164 return pMed->GetName();
2165 }
2166
isOwnDocument(const String & rFile) const2167 bool ScExternalRefManager::isOwnDocument(const String& rFile) const
2168 {
2169 return getOwnDocumentName().Equals(rFile);
2170 }
2171
convertToAbsName(String & rFile) const2172 void ScExternalRefManager::convertToAbsName(String& rFile) const
2173 {
2174 SfxObjectShell* pDocShell = mpDoc->GetDocumentShell();
2175 rFile = ScGlobal::GetAbsDocName(rFile, pDocShell);
2176 }
2177
getExternalFileId(const String & rFile)2178 sal_uInt16 ScExternalRefManager::getExternalFileId(const String& rFile)
2179 {
2180 vector<SrcFileData>::const_iterator itrBeg = maSrcFiles.begin(), itrEnd = maSrcFiles.end();
2181 vector<SrcFileData>::const_iterator itr = find_if(itrBeg, itrEnd, FindSrcFileByName(rFile));
2182 if (itr != itrEnd)
2183 {
2184 size_t nId = distance(itrBeg, itr);
2185 return static_cast<sal_uInt16>(nId);
2186 }
2187
2188 SrcFileData aData;
2189 aData.maFileName = rFile;
2190 maSrcFiles.push_back(aData);
2191 return static_cast<sal_uInt16>(maSrcFiles.size() - 1);
2192 }
2193
getExternalFileName(sal_uInt16 nFileId,bool bForceOriginal)2194 const String* ScExternalRefManager::getExternalFileName(sal_uInt16 nFileId, bool bForceOriginal)
2195 {
2196 if (nFileId >= maSrcFiles.size())
2197 return NULL;
2198
2199 if (bForceOriginal)
2200 return &maSrcFiles[nFileId].maFileName;
2201
2202 maybeCreateRealFileName(nFileId);
2203
2204 if (maSrcFiles[nFileId].maRealFileName.Len())
2205 return &maSrcFiles[nFileId].maRealFileName;
2206 else
2207 return &maSrcFiles[nFileId].maFileName;
2208 }
2209
hasExternalFile(sal_uInt16 nFileId) const2210 bool ScExternalRefManager::hasExternalFile(sal_uInt16 nFileId) const
2211 {
2212 return nFileId < maSrcFiles.size();
2213 }
2214
hasExternalFile(const String & rFile) const2215 bool ScExternalRefManager::hasExternalFile(const String& rFile) const
2216 {
2217 vector<SrcFileData>::const_iterator itrBeg = maSrcFiles.begin(), itrEnd = maSrcFiles.end();
2218 vector<SrcFileData>::const_iterator itr = find_if(itrBeg, itrEnd, FindSrcFileByName(rFile));
2219 return itr != itrEnd;
2220 }
2221
getExternalFileData(sal_uInt16 nFileId) const2222 const ScExternalRefManager::SrcFileData* ScExternalRefManager::getExternalFileData(sal_uInt16 nFileId) const
2223 {
2224 if (nFileId >= maSrcFiles.size())
2225 return NULL;
2226
2227 return &maSrcFiles[nFileId];
2228 }
2229
getRealTableName(sal_uInt16 nFileId,const String & rTabName) const2230 const String* ScExternalRefManager::getRealTableName(sal_uInt16 nFileId, const String& rTabName) const
2231 {
2232 return maRefCache.getRealTableName(nFileId, rTabName);
2233 }
2234
getRealRangeName(sal_uInt16 nFileId,const String & rRangeName) const2235 const String* ScExternalRefManager::getRealRangeName(sal_uInt16 nFileId, const String& rRangeName) const
2236 {
2237 return maRefCache.getRealRangeName(nFileId, rRangeName);
2238 }
2239
2240 template<typename MapContainer>
lcl_removeByFileId(sal_uInt16 nFileId,MapContainer & rMap)2241 void lcl_removeByFileId(sal_uInt16 nFileId, MapContainer& rMap)
2242 {
2243 typename MapContainer::iterator itr = rMap.find(nFileId);
2244 if (itr != rMap.end())
2245 rMap.erase(itr);
2246 }
2247
refreshNames(sal_uInt16 nFileId)2248 void ScExternalRefManager::refreshNames(sal_uInt16 nFileId)
2249 {
2250 maRefCache.clearCache(nFileId);
2251 lcl_removeByFileId(nFileId, maDocShells);
2252
2253 if (maDocShells.empty())
2254 maSrcDocTimer.Stop();
2255
2256 // Update all cells containing names from this source document.
2257 refreshAllRefCells(nFileId);
2258
2259 notifyAllLinkListeners(nFileId, LINK_MODIFIED);
2260 }
2261
breakLink(sal_uInt16 nFileId)2262 void ScExternalRefManager::breakLink(sal_uInt16 nFileId)
2263 {
2264 // Turn all formula cells referencing this external document into static
2265 // cells.
2266 RefCellMap::iterator itrRefs = maRefCells.find(nFileId);
2267 if (itrRefs != maRefCells.end())
2268 {
2269 // Make a copy because removing the formula cells below will modify
2270 // the original container.
2271 RefCellSet aSet = itrRefs->second;
2272 for_each(aSet.begin(), aSet.end(), ConvertFormulaToStatic(mpDoc));
2273 maRefCells.erase(nFileId);
2274 }
2275
2276 lcl_removeByFileId(nFileId, maDocShells);
2277
2278 if (maDocShells.empty())
2279 maSrcDocTimer.Stop();
2280
2281 LinkedDocMap::iterator itr = maLinkedDocs.find(nFileId);
2282 if (itr != maLinkedDocs.end())
2283 itr->second = false;
2284
2285 notifyAllLinkListeners(nFileId, LINK_BROKEN);
2286 }
2287
switchSrcFile(sal_uInt16 nFileId,const String & rNewFile,const String & rNewFilter)2288 void ScExternalRefManager::switchSrcFile(sal_uInt16 nFileId, const String& rNewFile, const String& rNewFilter)
2289 {
2290 maSrcFiles[nFileId].maFileName = rNewFile;
2291 maSrcFiles[nFileId].maRelativeName.Erase();
2292 maSrcFiles[nFileId].maRealFileName.Erase();
2293 if (!maSrcFiles[nFileId].maFilterName.Equals(rNewFilter))
2294 {
2295 // Filter type has changed.
2296 maSrcFiles[nFileId].maFilterName = rNewFilter;
2297 maSrcFiles[nFileId].maFilterOptions.Erase();
2298 }
2299 refreshNames(nFileId);
2300 }
2301
setRelativeFileName(sal_uInt16 nFileId,const String & rRelUrl)2302 void ScExternalRefManager::setRelativeFileName(sal_uInt16 nFileId, const String& rRelUrl)
2303 {
2304 if (nFileId >= maSrcFiles.size())
2305 return;
2306 maSrcFiles[nFileId].maRelativeName = rRelUrl;
2307 }
2308
setFilterData(sal_uInt16 nFileId,const String & rFilterName,const String & rOptions)2309 void ScExternalRefManager::setFilterData(sal_uInt16 nFileId, const String& rFilterName, const String& rOptions)
2310 {
2311 if (nFileId >= maSrcFiles.size())
2312 return;
2313 maSrcFiles[nFileId].maFilterName = rFilterName;
2314 maSrcFiles[nFileId].maFilterOptions = rOptions;
2315 }
2316
clear()2317 void ScExternalRefManager::clear()
2318 {
2319 DocShellMap::iterator itrEnd = maDocShells.end();
2320 for (DocShellMap::iterator itr = maDocShells.begin(); itr != itrEnd; ++itr)
2321 itr->second.maShell->DoClose();
2322
2323 maDocShells.clear();
2324 maSrcDocTimer.Stop();
2325 }
2326
hasExternalData() const2327 bool ScExternalRefManager::hasExternalData() const
2328 {
2329 return !maSrcFiles.empty();
2330 }
2331
resetSrcFileData(const String & rBaseFileUrl)2332 void ScExternalRefManager::resetSrcFileData(const String& rBaseFileUrl)
2333 {
2334 for (vector<SrcFileData>::iterator itr = maSrcFiles.begin(), itrEnd = maSrcFiles.end();
2335 itr != itrEnd; ++itr)
2336 {
2337 // Re-generate relative file name from the absolute file name.
2338 String aAbsName = itr->maRealFileName;
2339 if (!aAbsName.Len())
2340 aAbsName = itr->maFileName;
2341
2342 itr->maRelativeName = URIHelper::simpleNormalizedMakeRelative(
2343 rBaseFileUrl, aAbsName);
2344 }
2345 }
2346
updateAbsAfterLoad()2347 void ScExternalRefManager::updateAbsAfterLoad()
2348 {
2349 String aOwn( getOwnDocumentName() );
2350 for (vector<SrcFileData>::iterator itr = maSrcFiles.begin(), itrEnd = maSrcFiles.end();
2351 itr != itrEnd; ++itr)
2352 {
2353 // update maFileName to the real file name,
2354 // to be called when the original name is no longer needed (after CompileXML)
2355
2356 itr->maybeCreateRealFileName( aOwn );
2357 String aReal = itr->maRealFileName;
2358 if (aReal.Len())
2359 itr->maFileName = aReal;
2360 }
2361 }
2362
removeRefCell(ScFormulaCell * pCell)2363 void ScExternalRefManager::removeRefCell(ScFormulaCell* pCell)
2364 {
2365 for_each(maRefCells.begin(), maRefCells.end(), RemoveFormulaCell(pCell));
2366 }
2367
addLinkListener(sal_uInt16 nFileId,LinkListener * pListener)2368 void ScExternalRefManager::addLinkListener(sal_uInt16 nFileId, LinkListener* pListener)
2369 {
2370 LinkListenerMap::iterator itr = maLinkListeners.find(nFileId);
2371 if (itr == maLinkListeners.end())
2372 {
2373 pair<LinkListenerMap::iterator, bool> r = maLinkListeners.insert(
2374 LinkListenerMap::value_type(nFileId, LinkListeners()));
2375 if (!r.second)
2376 {
2377 DBG_ERROR("insertion of new link listener list failed");
2378 return;
2379 }
2380
2381 itr = r.first;
2382 }
2383
2384 LinkListeners& rList = itr->second;
2385 rList.insert(pListener);
2386 }
2387
removeLinkListener(sal_uInt16 nFileId,LinkListener * pListener)2388 void ScExternalRefManager::removeLinkListener(sal_uInt16 nFileId, LinkListener* pListener)
2389 {
2390 LinkListenerMap::iterator itr = maLinkListeners.find(nFileId);
2391 if (itr == maLinkListeners.end())
2392 // no listeners for a specified file.
2393 return;
2394
2395 LinkListeners& rList = itr->second;
2396 rList.erase(pListener);
2397
2398 if (rList.empty())
2399 // No more listeners for this file. Remove its entry.
2400 maLinkListeners.erase(itr);
2401 }
2402
removeLinkListener(LinkListener * pListener)2403 void ScExternalRefManager::removeLinkListener(LinkListener* pListener)
2404 {
2405 LinkListenerMap::iterator itr = maLinkListeners.begin(), itrEnd = maLinkListeners.end();
2406 for (; itr != itrEnd; ++itr)
2407 itr->second.erase(pListener);
2408 }
2409
notifyAllLinkListeners(sal_uInt16 nFileId,LinkUpdateType eType)2410 void ScExternalRefManager::notifyAllLinkListeners(sal_uInt16 nFileId, LinkUpdateType eType)
2411 {
2412 LinkListenerMap::iterator itr = maLinkListeners.find(nFileId);
2413 if (itr == maLinkListeners.end())
2414 // no listeners for a specified file.
2415 return;
2416
2417 LinkListeners& rList = itr->second;
2418 for_each(rList.begin(), rList.end(), NotifyLinkListener(nFileId, eType));
2419 }
2420
purgeStaleSrcDocument(sal_Int32 nTimeOut)2421 void ScExternalRefManager::purgeStaleSrcDocument(sal_Int32 nTimeOut)
2422 {
2423 DocShellMap aNewDocShells;
2424 DocShellMap::iterator itr = maDocShells.begin(), itrEnd = maDocShells.end();
2425 for (; itr != itrEnd; ++itr)
2426 {
2427 // in 100th of a second.
2428 sal_Int32 nSinceLastAccess = (Time() - itr->second.maLastAccess).GetTime();
2429 if (nSinceLastAccess < nTimeOut)
2430 aNewDocShells.insert(*itr);
2431 }
2432 maDocShells.swap(aNewDocShells);
2433
2434 if (maDocShells.empty())
2435 maSrcDocTimer.Stop();
2436 }
2437
getMappedNumberFormat(sal_uInt16 nFileId,sal_uInt32 nNumFmt,ScDocument * pSrcDoc)2438 sal_uInt32 ScExternalRefManager::getMappedNumberFormat(sal_uInt16 nFileId, sal_uInt32 nNumFmt, ScDocument* pSrcDoc)
2439 {
2440 NumFmtMap::iterator itr = maNumFormatMap.find(nFileId);
2441 if (itr == maNumFormatMap.end())
2442 {
2443 // Number formatter map is not initialized for this external document.
2444 pair<NumFmtMap::iterator, bool> r = maNumFormatMap.insert(
2445 NumFmtMap::value_type(nFileId, SvNumberFormatterMergeMap()));
2446
2447 if (!r.second)
2448 // insertion failed.
2449 return nNumFmt;
2450
2451 itr = r.first;
2452 mpDoc->GetFormatTable()->MergeFormatter( *pSrcDoc->GetFormatTable());
2453 SvNumberFormatterMergeMap aMap = mpDoc->GetFormatTable()->ConvertMergeTableToMap();
2454 itr->second.swap(aMap);
2455 }
2456 const SvNumberFormatterMergeMap& rMap = itr->second;
2457 SvNumberFormatterMergeMap::const_iterator itrNumFmt = rMap.find(nNumFmt);
2458 if (itrNumFmt != rMap.end())
2459 // mapped value found.
2460 return itrNumFmt->second;
2461
2462 return nNumFmt;
2463 }
2464
IMPL_LINK(ScExternalRefManager,TimeOutHdl,AutoTimer *,pTimer)2465 IMPL_LINK(ScExternalRefManager, TimeOutHdl, AutoTimer*, pTimer)
2466 {
2467 if (pTimer == &maSrcDocTimer)
2468 purgeStaleSrcDocument(SRCDOC_LIFE_SPAN);
2469
2470 return 0;
2471 }
2472