1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
3 * This file is part of the LibreOffice project.
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
9 * This file incorporates work covered by the following license notice:
11 * Licensed to the Apache Software Foundation (ASF) under one or more
12 * contributor license agreements. See the NOTICE file distributed
13 * with this work for additional information regarding copyright
14 * ownership. The ASF licenses this file to you under the Apache
15 * License, Version 2.0 (the "License"); you may not use this file
16 * except in compliance with the License. You may obtain a copy of
17 * the License at http://www.apache.org/licenses/LICENSE-2.0 .
20 #include <sal/config.h>
22 #include <com/sun/star/task/InteractionHandler.hpp>
24 #include <sfx2/sfxsids.hrc>
25 #include <sfx2/app.hxx>
26 #include <svl/itemset.hxx>
27 #include <svl/stritem.hxx>
28 #include <sfx2/docfile.hxx>
29 #include <sfx2/docfilt.hxx>
30 #include <sfx2/fcontnr.hxx>
31 #include <sfx2/frame.hxx>
32 #include <sfx2/linkmgr.hxx>
34 #include <vcl/weld.hxx>
35 #include <tools/urlobj.hxx>
36 #include <unotools/transliterationwrapper.hxx>
37 #include <comphelper/configuration.hxx>
38 #include <comphelper/processfactory.hxx>
40 #include <tablink.hxx>
42 #include <scextopt.hxx>
43 #include <document.hxx>
45 #include <globstr.hrc>
46 #include <scresid.hxx>
47 #include <undoblk.hxx>
48 #include <undotab.hxx>
51 #include <dociter.hxx>
52 #include <formula/opcode.hxx>
53 #include <formulaiter.hxx>
54 #include <tokenarray.hxx>
59 Link
<sfx2::SvBaseLink
&,void> m_aEndEditLink
;
61 TableLink_Impl() : m_pDocSh( nullptr ) {}
64 ScTableLink::ScTableLink(ScDocShell
* pShell
, OUString aFile
,
65 OUString aFilter
, OUString aOpt
,
66 sal_Int32 nRefreshDelaySeconds
):
67 ::sfx2::SvBaseLink(SfxLinkUpdateMode::ONCALL
,SotClipboardFormatId::SIMPLE_FILE
),
68 ScRefreshTimer( nRefreshDelaySeconds
),
69 pImpl( new TableLink_Impl
),
70 aFileName(std::move(aFile
)),
71 aFilterName(std::move(aFilter
)),
72 aOptions(std::move(aOpt
)),
77 pImpl
->m_pDocSh
= pShell
;
80 ScTableLink::~ScTableLink()
85 ScDocument
& rDoc
= pImpl
->m_pDocSh
->GetDocument();
86 SCTAB nCount
= rDoc
.GetTableCount();
87 for (SCTAB nTab
=0; nTab
<nCount
; nTab
++)
88 if (rDoc
.IsLinked(nTab
) && aFileName
== rDoc
.GetLinkDoc(nTab
))
89 rDoc
.SetLink( nTab
, ScLinkMode::NONE
, u
""_ustr
, u
""_ustr
, u
""_ustr
, u
""_ustr
, 0 );
92 void ScTableLink::Edit(weld::Window
* pParent
, const Link
<SvBaseLink
&,void>& rEndEditHdl
)
94 pImpl
->m_aEndEditLink
= rEndEditHdl
;
97 SvBaseLink::Edit( pParent
, LINK( this, ScTableLink
, TableEndEditHdl
) );
100 ::sfx2::SvBaseLink::UpdateResult
ScTableLink::DataChanged(
101 const OUString
&, const css::uno::Any
& )
103 sfx2::LinkManager
* pLinkManager
=pImpl
->m_pDocSh
->GetDocument().GetLinkManager();
104 if (pLinkManager
!=nullptr)
106 OUString aFile
, aFilter
;
107 sfx2::LinkManager::GetDisplayNames(this, nullptr, &aFile
, nullptr, &aFilter
);
109 // the file dialog returns the filter name with the application prefix
111 ScDocumentLoader::RemoveAppPrefix( aFilter
);
114 Refresh( aFile
, aFilter
, nullptr, GetRefreshDelaySeconds() ); // don't load twice
119 void ScTableLink::Closed()
122 ScDocument
& rDoc
= pImpl
->m_pDocSh
->GetDocument();
123 bool bUndo (rDoc
.IsUndoEnabled());
125 if (bAddUndo
&& bUndo
)
127 pImpl
->m_pDocSh
->GetUndoManager()->AddUndoAction(
128 std::make_unique
<ScUndoRemoveLink
>( pImpl
->m_pDocSh
, aFileName
) );
130 bAddUndo
= false; // only once
133 // connection gets cancelled in the dtor
135 SvBaseLink::Closed();
138 bool ScTableLink::IsUsed() const
140 return pImpl
->m_pDocSh
->GetDocument().HasLink( aFileName
, aFilterName
, aOptions
);
143 bool ScTableLink::Refresh(const OUString
& rNewFile
, const OUString
& rNewFilter
,
144 const OUString
* pNewOptions
, sal_Int32 nNewRefreshDelaySeconds
)
148 if (rNewFile
.isEmpty() || rNewFilter
.isEmpty())
151 OUString aNewUrl
= ScGlobal::GetAbsDocName(rNewFile
, pImpl
->m_pDocSh
);
152 bool bNewUrlName
= aFileName
!= aNewUrl
;
154 std::shared_ptr
<const SfxFilter
> pFilter
= pImpl
->m_pDocSh
->GetFactory().GetFilterContainer()->GetFilter4FilterName(rNewFilter
);
158 ScDocument
& rDoc
= pImpl
->m_pDocSh
->GetDocument();
159 rDoc
.SetInLinkUpdate( true );
161 bool bUndo(rDoc
.IsUndoEnabled());
163 // if new filter has been selected, forget options
164 if (aFilterName
!= rNewFilter
)
166 if ( pNewOptions
) // options hard-specified?
167 aOptions
= *pNewOptions
;
169 // always create ItemSet, so that DocShell can set the options
170 auto pSet
= std::make_shared
<SfxAllItemSet
>( SfxGetpApp()->GetPool() );
171 if (!aOptions
.isEmpty())
172 pSet
->Put( SfxStringItem( SID_FILE_FILTEROPTIONS
, aOptions
) );
174 SfxMedium
* pMed
= new SfxMedium(aNewUrl
, StreamMode::STD_READ
, std::move(pFilter
), std::move(pSet
));
176 if ( bInEdit
) // only if using the edit dialog,
177 pMed
->UseInteractionHandler(true); // enable the filter options dialog
179 // aRef->DoClose() will be called explicitly, but it is still more safe to use SfxObjectShellLock here
180 rtl::Reference
<ScDocShell
> pSrcShell
= new ScDocShell(SfxModelFlags::EMBEDDED_OBJECT
| SfxModelFlags::DISABLE_EMBEDDED_SCRIPTS
);
181 pSrcShell
->DoLoad(pMed
);
183 // options might have been set
184 OUString aNewOpt
= ScDocumentLoader::GetOptions(*pMed
);
185 if (aNewOpt
.isEmpty())
190 ScDocumentUniquePtr pUndoDoc
;
192 if (bAddUndo
&& bUndo
)
193 pUndoDoc
.reset(new ScDocument( SCDOCMODE_UNDO
));
197 ScDocShellModificator
aModificator( *pImpl
->m_pDocSh
);
199 bool bNotFound
= false;
200 ScDocument
& rSrcDoc
= pSrcShell
->GetDocument();
202 // from text filters that don't set the table name,
203 // use the one table regardless of link table name
204 bool bAutoTab
= (rSrcDoc
.GetTableCount() == 1) &&
205 ScDocShell::HasAutomaticTableName( rNewFilter
);
207 SCTAB nCount
= rDoc
.GetTableCount();
208 for (SCTAB nTab
=0; nTab
<nCount
; nTab
++)
210 ScLinkMode nMode
= rDoc
.GetLinkMode(nTab
);
211 if (nMode
!= ScLinkMode::NONE
&& aFileName
== rDoc
.GetLinkDoc(nTab
))
213 OUString aTabName
= rDoc
.GetLinkTab(nTab
);
217 if (bAddUndo
&& bUndo
)
220 pUndoDoc
->InitUndo( rDoc
, nTab
, nTab
, true, true );
222 pUndoDoc
->AddUndoTab( nTab
, nTab
, true, true );
224 ScRange
aRange(0,0,nTab
,rDoc
.MaxCol(),rDoc
.MaxRow(),nTab
);
225 rDoc
.CopyToDocument(aRange
, InsertDeleteFlags::ALL
, false, *pUndoDoc
);
226 pUndoDoc
->TransferDrawPage( rDoc
, nTab
, nTab
);
227 pUndoDoc
->SetLink( nTab
, nMode
, aFileName
, aFilterName
,
228 aOptions
, aTabName
, GetRefreshDelaySeconds() );
229 pUndoDoc
->SetTabBgColor( nTab
, rDoc
.GetTabBgColor(nTab
) );
232 // adjust table name of an ExtDocRef
234 if ( bNewUrlName
&& nMode
== ScLinkMode::VALUE
)
237 rDoc
.GetName( nTab
, aName
);
238 if ( ScGlobal::GetTransliteration().isEqual(
239 ScGlobal::GetDocTabName( aFileName
, aTabName
), aName
) )
241 rDoc
.RenameTab( nTab
,
242 ScGlobal::GetDocTabName( aNewUrl
, aTabName
),
243 true/*bExternalDocument*/ );
251 /* #i71497# check if external document is loaded successfully,
252 otherwise we may find the empty default sheet "Sheet1" in
253 rSrcDoc, even if the document does not exist. */
254 if( pMed
->GetErrorIgnoreWarning() == ERRCODE_NONE
)
256 // no sheet name -> use first sheet
257 if ( !aTabName
.isEmpty() && !bAutoTab
)
258 bFound
= rSrcDoc
.GetTable( aTabName
, nSrcTab
);
264 rDoc
.TransferTab( rSrcDoc
, nSrcTab
, nTab
, false, // don't insert anew
265 (nMode
== ScLinkMode::VALUE
) ); // only values?
268 rDoc
.DeleteAreaTab( 0,0,rDoc
.MaxCol(),rDoc
.MaxRow(), nTab
, InsertDeleteFlags::ALL
);
270 bool bShowError
= true;
271 if ( nMode
== ScLinkMode::VALUE
)
273 // Value link (used with external references in formulas):
274 // Look for formulas that reference the sheet, and put errors in the referenced cells.
276 ScRangeList aErrorCells
; // cells on the linked sheets that need error values
278 ScCellIterator
aIter(rDoc
, ScRange(0,0,0,rDoc
.MaxCol(),rDoc
.MaxRow(),MAXTAB
)); // all sheets
279 for (bool bHas
= aIter
.first(); bHas
; bHas
= aIter
.next())
281 if (aIter
.getType() != CELLTYPE_FORMULA
)
284 ScFormulaCell
* pCell
= aIter
.getFormulaCell();
285 ScDetectiveRefIter
aRefIter(rDoc
, pCell
);
287 while ( aRefIter
.GetNextRef( aRefRange
) )
289 if ( aRefRange
.aStart
.Tab() <= nTab
&& aRefRange
.aEnd
.Tab() >= nTab
)
291 // use first cell of range references (don't fill potentially large ranges)
293 aErrorCells
.Join( ScRange( aRefRange
.aStart
) );
298 size_t nRanges
= aErrorCells
.size();
299 if ( nRanges
) // found any?
301 ScTokenArray
aTokenArr(rDoc
);
302 aTokenArr
.AddOpCode( ocNotAvail
);
303 aTokenArr
.AddOpCode( ocOpen
);
304 aTokenArr
.AddOpCode( ocClose
);
305 aTokenArr
.AddOpCode( ocStop
);
307 for (size_t nPos
=0; nPos
< nRanges
; nPos
++)
309 const ScRange
& rRange
= aErrorCells
[ nPos
];
310 SCCOL nStartCol
= rRange
.aStart
.Col();
311 SCROW nStartRow
= rRange
.aStart
.Row();
312 SCCOL nEndCol
= rRange
.aEnd
.Col();
313 SCROW nEndRow
= rRange
.aEnd
.Row();
314 for (SCROW nRow
=nStartRow
; nRow
<=nEndRow
; nRow
++)
315 for (SCCOL nCol
=nStartCol
; nCol
<=nEndCol
; nCol
++)
317 ScAddress
aDestPos( nCol
, nRow
, nTab
);
318 rDoc
.SetFormula(aDestPos
, aTokenArr
);
324 // if no references were found, insert error message (don't leave the sheet empty)
329 // Normal link or no references: put error message on sheet.
331 rDoc
.SetString( 0,0,nTab
, ScResId(STR_LINKERROR
) );
332 rDoc
.SetString( 0,1,nTab
, ScResId(STR_LINKERRORFILE
) );
333 rDoc
.SetString( 1,1,nTab
, aNewUrl
);
334 rDoc
.SetString( 0,2,nTab
, ScResId(STR_LINKERRORTAB
) );
335 rDoc
.SetString( 1,2,nTab
, aTabName
);
341 if ( bNewUrlName
|| aFilterName
!= rNewFilter
||
342 aOptions
!= aNewOpt
|| pNewOptions
||
343 nNewRefreshDelaySeconds
!= GetRefreshDelaySeconds() )
344 rDoc
.SetLink( nTab
, nMode
, aNewUrl
, rNewFilter
, aNewOpt
,
345 aTabName
, nNewRefreshDelaySeconds
);
349 // memorize new settings
353 if (aFilterName
!= rNewFilter
)
354 aFilterName
= rNewFilter
;
355 if (aOptions
!= aNewOpt
)
360 pSrcShell
->DoClose();
364 if (bAddUndo
&& bUndo
)
365 pImpl
->m_pDocSh
->GetUndoManager()->AddUndoAction(
366 std::make_unique
<ScUndoRefreshLink
>( pImpl
->m_pDocSh
, std::move(pUndoDoc
) ) );
368 // Paint (may be several tables)
370 pImpl
->m_pDocSh
->PostPaint( ScRange(0,0,0,rDoc
.MaxCol(),rDoc
.MaxRow(),MAXTAB
),
371 PaintPartFlags::Grid
| PaintPartFlags::Top
| PaintPartFlags::Left
| PaintPartFlags::Extras
);
372 aModificator
.SetDocumentModified();
379 rDoc
.SetInLinkUpdate( false );
381 // notify Uno objects (for XRefreshListener)
382 //! also notify Uno objects if file name was changed!
383 ScLinkRefreshedHint aHint
;
384 aHint
.SetSheetLink( aFileName
);
385 rDoc
.BroadcastUno( aHint
);
390 IMPL_LINK( ScTableLink
, TableEndEditHdl
, ::sfx2::SvBaseLink
&, rLink
, void )
392 pImpl
->m_aEndEditLink
.Call( rLink
);
396 // === ScDocumentLoader ==================================================
398 OUString
ScDocumentLoader::GetOptions( const SfxMedium
& rMedium
)
400 if ( const SfxStringItem
* pItem
= rMedium
.GetItemSet().GetItemIfSet( SID_FILE_FILTEROPTIONS
) )
401 return pItem
->GetValue();
406 bool ScDocumentLoader::GetFilterName( const OUString
& rFileName
,
407 OUString
& rFilter
, OUString
& rOptions
,
408 bool bWithContent
, bool bWithInteraction
)
410 SfxObjectShell
* pDocSh
= SfxObjectShell::GetFirst( checkSfxObjectShell
<ScDocShell
> );
413 if ( pDocSh
->HasName() )
415 SfxMedium
* pMed
= pDocSh
->GetMedium();
416 if ( pMed
->GetName() == rFileName
)
418 rFilter
= pMed
->GetFilter()->GetFilterName();
419 rOptions
= GetOptions(*pMed
);
423 pDocSh
= SfxObjectShell::GetNext( *pDocSh
, checkSfxObjectShell
<ScDocShell
> );
426 INetURLObject
aUrl( rFileName
);
427 INetProtocol eProt
= aUrl
.GetProtocol();
428 if ( eProt
== INetProtocol::NotValid
) // invalid URL?
429 return false; // abort without creating a medium
433 std::shared_ptr
<const SfxFilter
> pSfxFilter
;
434 SfxMedium
aMedium( rFileName
, StreamMode::STD_READ
);
435 if (aMedium
.GetErrorIgnoreWarning() == ERRCODE_NONE
&& !comphelper::IsFuzzing())
437 if ( bWithInteraction
)
438 aMedium
.UseInteractionHandler(true); // #i73992# no longer called from GuessFilter
440 SfxFilterMatcher
aMatcher(u
"scalc"_ustr
);
442 aMatcher
.GuessFilter( aMedium
, pSfxFilter
);
444 aMatcher
.GuessFilterIgnoringContent( aMedium
, pSfxFilter
);
448 if ( aMedium
.GetErrorIgnoreWarning() == ERRCODE_NONE
)
451 rFilter
= pSfxFilter
->GetFilterName();
453 rFilter
= ScDocShell::GetOwnFilterName(); // otherwise Calc file
454 bOK
= !rFilter
.isEmpty();
460 void ScDocumentLoader::RemoveAppPrefix( OUString
& rFilterName
)
462 OUString
aAppPrefix( STRING_SCAPP
+ ": ");
463 if (rFilterName
.startsWith( aAppPrefix
))
464 rFilterName
= rFilterName
.copy( aAppPrefix
.getLength());
467 SfxMedium
* ScDocumentLoader::CreateMedium( const OUString
& rFileName
, std::shared_ptr
<const SfxFilter
> const & pFilter
,
468 const OUString
& rOptions
, weld::Window
* pInteractionParent
)
470 // Always create SfxItemSet so ScDocShell can set options.
471 auto pSet
= std::make_shared
<SfxAllItemSet
>( SfxGetpApp()->GetPool() );
472 if ( !rOptions
.isEmpty() )
473 pSet
->Put( SfxStringItem( SID_FILE_FILTEROPTIONS
, rOptions
) );
475 if (pInteractionParent
)
477 const css::uno::Reference
<css::uno::XComponentContext
>& xContext
= comphelper::getProcessComponentContext();
478 css::uno::Reference
<css::task::XInteractionHandler
> xIHdl(css::task::InteractionHandler::createWithParent(xContext
,
479 pInteractionParent
->GetXWindow()), css::uno::UNO_QUERY_THROW
);
480 pSet
->Put(SfxUnoAnyItem(SID_INTERACTIONHANDLER
, css::uno::Any(xIHdl
)));
483 SfxMedium
*pRet
= new SfxMedium( rFileName
, StreamMode::STD_READ
, pFilter
, std::move(pSet
) );
484 if (pInteractionParent
)
485 pRet
->UseInteractionHandler(true); // to enable the filter options dialog
489 ScDocumentLoader::ScDocumentLoader(const OUString
& rFileName
,
490 OUString
& rFilterName
, OUString
& rOptions
,
491 sal_uInt32 nRekCnt
, weld::Window
* pInteractionParent
,
492 const css::uno::Reference
<css::io::XInputStream
>& xInputStream
)
495 if ( rFilterName
.isEmpty() )
496 GetFilterName(rFileName
, rFilterName
, rOptions
, true, pInteractionParent
!= nullptr);
498 std::shared_ptr
<const SfxFilter
> pFilter
= ScDocShell::Factory().GetFilterContainer()->GetFilter4FilterName( rFilterName
);
500 pMedium
= CreateMedium(rFileName
, pFilter
, rOptions
, pInteractionParent
);
501 if (xInputStream
.is())
502 pMedium
->setStreamToLoadFrom(xInputStream
, true);
503 if ( pMedium
->GetErrorIgnoreWarning() != ERRCODE_NONE
)
506 pDocShell
= new ScDocShell( SfxModelFlags::EMBEDDED_OBJECT
| SfxModelFlags::DISABLE_EMBEDDED_SCRIPTS
);
508 ScDocument
& rDoc
= pDocShell
->GetDocument();
509 ScExtDocOptions
* pExtDocOpt
= rDoc
.GetExtDocOptions();
512 rDoc
.SetExtDocOptions( std::make_unique
<ScExtDocOptions
>() );
513 pExtDocOpt
= rDoc
.GetExtDocOptions();
515 pExtDocOpt
->GetDocSettings().mnLinkCnt
= nRekCnt
;
517 pDocShell
->DoLoad( pMedium
);
519 OUString aNew
= GetOptions(*pMedium
); // options are set per dialog on load
520 if (!aNew
.isEmpty() && aNew
!= rOptions
)
524 ScDocumentLoader::~ScDocumentLoader()
527 pDocShell
->DoClose();
532 void ScDocumentLoader::ReleaseDocRef()
536 // release reference without calling DoClose - caller must
537 // have another reference to the doc and call DoClose later
544 ScDocument
* ScDocumentLoader::GetDocument()
546 return pDocShell
? &pDocShell
->GetDocument() : nullptr;
549 bool ScDocumentLoader::IsError() const
551 if ( pDocShell
&& pMedium
)
552 return pMedium
->GetErrorIgnoreWarning() != ERRCODE_NONE
;
557 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */