Quellcodebibliothek Statistik Leitseite products/Sources/formale Sprachen/C/LibreOffice/sc/source/ui/docshell/   (Office von Apache Version 25.8.3.2©)  Datei vom 5.10.2025 mit Größe 132 kB image not shown  

Quelle  docsh.cxx   Sprache: C

 
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */


#include <sal/config.h>

#include <docsh.hxx>

#include <config_features.h>
#include <scitems.hxx>
#include <sc.hrc>
#include <vcl/errinf.hxx>
#include <editeng/justifyitem.hxx>
#include <comphelper/fileformat.h>
#include <comphelper/classids.hxx>
#include <comphelper/propertyvalue.hxx>
#include <formula/errorcodes.hxx>
#include <vcl/stdtext.hxx>
#include <vcl/syswin.hxx>
#include <vcl/svapp.hxx>
#include <vcl/virdev.hxx>
#include <vcl/weld.hxx>
#include <rtl/bootstrap.hxx>
#include <rtl/tencinfo.h>
#include <sal/log.hxx>
#include <svl/PasswordHelper.hxx>
#include <sfx2/app.hxx>
#include <sfx2/bindings.hxx>
#include <sfx2/dinfdlg.hxx>
#include <sfx2/docfile.hxx>
#include <sfx2/event.hxx>
#include <sfx2/docfilt.hxx>
#include <sfx2/lokhelper.hxx>
#include <sfx2/objface.hxx>
#include <sfx2/viewfrm.hxx>
#include <sfx2/infobar.hxx>
#include <svl/documentlockfile.hxx>
#include <svl/fstathelper.hxx>
#include <svl/sharecontrolfile.hxx>
#include <svl/urihelper.hxx>
#include <osl/file.hxx>
#include <chgtrack.hxx>
#include <chgviset.hxx>
#include <com/sun/star/awt/Key.hpp>
#include <com/sun/star/awt/KeyModifier.hpp>
#include <com/sun/star/container/XContentEnumerationAccess.hpp>
#include <com/sun/star/document/UpdateDocMode.hpp>
#include <com/sun/star/script/vba/VBAEventId.hpp>
#include <com/sun/star/script/vba/VBAScriptEventId.hpp>
#include <com/sun/star/script/vba/XVBAEventProcessor.hpp>
#include <com/sun/star/script/vba/XVBAScriptListener.hpp>
#include <com/sun/star/script/vba/XVBACompatibility.hpp>
#include <com/sun/star/sheet/XSpreadsheetView.hpp>
#include <com/sun/star/task/XJob.hpp>
#include <com/sun/star/ui/theModuleUIConfigurationManagerSupplier.hpp>
#include <com/sun/star/ui/XAcceleratorConfiguration.hpp>
#include <com/sun/star/util/VetoException.hpp>
#include <com/sun/star/lang/XSingleComponentFactory.hpp>
#include <ooo/vba/excel/XWorkbook.hpp>
#include <comphelper/diagnose_ex.hxx>

#include <config_folders.h>

#include <scabstdlg.hxx>
#include <sot/formats.hxx>
#include <svx/compatflags.hxx>
#include <svx/dialogs.hrc>
#include <svx/svdpagv.hxx>
#include <svx/svdpage.hxx>
#include <docmodel/theme/Theme.hxx>

#include <inputopt.hxx>
#include <formulacell.hxx>
#include <global.hxx>
#include <filter.hxx>
#include <scmod.hxx>
#include <tabvwsh.hxx>
#include <docfunc.hxx>
#include <imoptdlg.hxx>
#include <impex.hxx>
#include <scresid.hxx>
#include <strings.hrc>
#include <globstr.hrc>
#include <scerrors.hxx>
#include <brdcst.hxx>
#include <stlpool.hxx>
#include <autostyl.hxx>
#include <attrib.hxx>
#include <asciiopt.hxx>
#include <progress.hxx>
#include <pntlock.hxx>
#include <docuno.hxx>
#include <appoptio.hxx>
#include <formulaopt.hxx>
#include <scdll.hxx>
#include <detdata.hxx>
#include <printfun.hxx>
#include <dociter.hxx>
#include <cellform.hxx>
#include <chartlis.hxx>
#include <hints.hxx>
#include <xmlwrap.hxx>
#include <drwlayer.hxx>
#include <dbdata.hxx>
#include <scextopt.hxx>
#include <compiler.hxx>
#include <warnpassword.hxx>
#include <sheetdata.hxx>
#include <table.hxx>
#include <tabprotection.hxx>
#include <docparam.hxx>
#include "docshimp.hxx"
#include <sizedev.hxx>
#include <undomanager.hxx>
#include <refreshtimerprotector.hxx>

#include <officecfg/Office/Calc.hxx>
#include <comphelper/processfactory.hxx>
#include <comphelper/string.hxx>
#include <unotools/configmgr.hxx>
#include <unotools/mediadescriptor.hxx>
#include <unotools/tempfile.hxx>
#include <unotools/ucbstreamhelper.hxx>
#include <uiitems.hxx>
#include <dpobject.hxx>
#include <markdata.hxx>
#include <docoptio.hxx>
#include <orcusfilters.hxx>
#include <datastream.hxx>
#include <documentlinkmgr.hxx>
#include <refupdatecontext.hxx>
#include <DocumentModelAccessor.hxx>

#include <memory>
#include <vector>

#include <comphelper/lok.hxx>
#include <svtools/sfxecode.hxx>
#include <unotools/pathoptions.hxx>

using namespace com::sun::star;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::lang::XMultiServiceFactory;
using std::shared_ptr;
using ::std::vector;

//  Filter names (like in sclib.cxx)

constexpr OUStringLiteral pFilterSc50 = u"StarCalc 5.0";
const char pFilterXML[]      = "StarOffice XML (Calc)";
constexpr OUString pFilterLotus = u"Lotus"_ustr;
const char pFilterQPro6[]    = "Quattro Pro 6.0";
const char16_t pFilterExcel4[] = u"MS Excel 4.0";
const char16_t pFilterEx4Temp[] = u"MS Excel 4.0 Vorlage/Template";
const char pFilterExcel5[]   = "MS Excel 5.0/95";
const char pFilterEx5Temp[]  = "MS Excel 5.0/95 Vorlage/Template";
const char pFilterExcel95[]  = "MS Excel 95";
const char pFilterEx95Temp[] = "MS Excel 95 Vorlage/Template";
const char pFilterExcel97[]  = "MS Excel 97";
const char pFilterEx97Temp[] = "MS Excel 97 Vorlage/Template";
constexpr OUString pFilterDBase = u"dBase"_ustr;
constexpr OUString pFilterDif = u"DIF"_ustr;
const char16_t pFilterSylk[] = u"SYLK";
constexpr OUString pFilterHtml = u"HTML (StarCalc)"_ustr;
constexpr OUString pFilterHtmlWebQ = u"calc_HTML_WebQuery"_ustr;
const char16_t pFilterRtf[]  = u"Rich Text Format (StarCalc)";

#define ShellClass_ScDocShell
#include <scslots.hxx>

SFX_IMPL_INTERFACE(ScDocShell,SfxObjectShell)

void ScDocShell::InitInterface_Impl()
{
}

//  GlobalName of the current version:
SFX_IMPL_OBJECTFACTORY( ScDocShell, SvGlobalName(SO3_SC_CLASSID), u"scalc"_ustr )


void ScDocShell::FillClass( SvGlobalName* pClassName,
                                        SotClipboardFormatId* pFormat,
                                        OUString* pFullTypeName,
                                        sal_Int32 nFileFormat,
                                        bool bTemplate /* = false */) const
{
    if ( nFileFormat == SOFFICE_FILEFORMAT_60 )
    {
        *pClassName     = SvGlobalName( SO3_SC_CLASSID_60 );
        *pFormat        = SotClipboardFormatId::STARCALC_60;
        *pFullTypeName  = ScResId( SCSTR_LONG_SCDOC_NAME_60 );
    }
    else if ( nFileFormat == SOFFICE_FILEFORMAT_8 )
    {
        *pClassName     = SvGlobalName( SO3_SC_CLASSID_60 );
        *pFormat        = bTemplate ? SotClipboardFormatId::STARCALC_8_TEMPLATE : SotClipboardFormatId::STARCALC_8;
        *pFullTypeName  = ScResId( SCSTR_LONG_SCDOC_NAME_80 );
    }
    else
    {
        OSL_FAIL("Which version?");
    }
}

std::set<Color> ScDocShell::GetDocColors()
{
    return m_pDocument->GetDocColors();
}

std::shared_ptr<sfx::IDocumentModelAccessor> ScDocShell::GetDocumentModelAccessor() const
{
    std::shared_ptr<sfx::IDocumentModelAccessor> pReturn;
    pReturn.reset(new sc::DocumentModelAccessor(m_pDocument));
    return pReturn;
}

std::shared_ptr<model::ColorSet> ScDocShell::GetThemeColors()
{
    ScTabViewShell* pShell = GetBestViewShell();
    if (!pShell)
        return {};

    SdrModel* pSdrModel = GetDocument().GetDrawLayer();
    if (!pSdrModel)
        return {};

    auto const& pTheme = pSdrModel->getTheme();
    if (!pTheme)
        return {};

    return pTheme->getColorSet();
}

void ScDocShell::DoEnterHandler()
{
    ScTabViewShell* pViewSh = ScTabViewShell::GetActiveViewShell();
    if (pViewSh && &pViewSh->GetViewData().GetDocShell() == this)
        ScModule::get()->InputEnterHandler();
}

SCTAB ScDocShell::GetSaveTab()
{
    SCTAB nTab = 0;
    ScTabViewShell* pSh = GetBestViewShell();
    if (pSh)
    {
        const ScMarkData& rMark = pSh->GetViewData().GetMarkData();
        nTab = rMark.GetFirstSelected();
    }
    return nTab;
}

HiddenInformation ScDocShell::GetHiddenInformationState( HiddenInformation nStates )
{
    // get global state like HiddenInformation::DOCUMENTVERSIONS
    HiddenInformation nState = SfxObjectShell::GetHiddenInformationState( nStates );

    if ( nStates & HiddenInformation::RECORDEDCHANGES )
    {
        if ( m_pDocument->GetChangeTrack() && m_pDocument->GetChangeTrack()->GetFirst() )
          nState |= HiddenInformation::RECORDEDCHANGES;
    }
    if ( nStates & HiddenInformation::NOTES )
    {
        SCTAB nTableCount = m_pDocument->GetTableCount();
        bool bFound = false;
        for (SCTAB nTab = 0; nTab < nTableCount && !bFound; ++nTab)
        {
            if (m_pDocument->HasTabNotes(nTab)) //TODO:
                bFound = true;
        }

        if (bFound)
            nState |= HiddenInformation::NOTES;
    }

    return nState;
}

void ScDocShell::BeforeXMLLoading()
{
    m_pDocument->EnableIdle(false);

    // prevent unnecessary broadcasts and updates
    OSL_ENSURE(m_pModificator == nullptr, "The Modificator should not exist");
    m_pModificator.reset( new ScDocShellModificator( *this ) );

    m_pDocument->SetImportingXML( true );
    m_pDocument->EnableExecuteLink( false );   // #i101304# to be safe, prevent nested loading from external references
    m_pDocument->EnableUndo( false );
    // prevent unnecessary broadcasts and "half way listeners"
    m_pDocument->SetInsertingFromOtherDoc( true );
}

void ScDocShell::AfterXMLLoading(bool bRet)
{
    if (GetCreateMode() != SfxObjectCreateMode::ORGANIZER)
    {
        UpdateLinks();
        // don't prevent establishing of listeners anymore
        m_pDocument->SetInsertingFromOtherDoc( false );
        if ( bRet )
        {
            ScChartListenerCollection* pChartListener = m_pDocument->GetChartListenerCollection();
            if (pChartListener)
                pChartListener->UpdateDirtyCharts();

            // #95582#; set the table names of linked tables to the new path
            SCTAB nTabCount = m_pDocument->GetTableCount();
            for (SCTAB i = 0; i < nTabCount; ++i)
            {
                if (m_pDocument->IsLinked( i ))
                {
                    OUString aName;
                    m_pDocument->GetName(i, aName);
                    OUString aLinkTabName = m_pDocument->GetLinkTab(i);
                    sal_Int32 nLinkTabNameLength = aLinkTabName.getLength();
                    sal_Int32 nNameLength = aName.getLength();
                    if (nLinkTabNameLength < nNameLength)
                    {

                        // remove the quotes on begin and end of the docname and restore the escaped quotes
                        const sal_Unicode* pNameBuffer = aName.getStr();
                        if ( *pNameBuffer == '\'' && // all docnames have to have a ' character on the first pos
                            ScGlobal::UnicodeStrChr( pNameBuffer, SC_COMPILER_FILE_TAB_SEP ) )
                        {
                            OUStringBuffer aDocURLBuffer;
                            bool bQuote = true// Document name is always quoted
                            ++pNameBuffer;
                            while ( bQuote && *pNameBuffer )
                            {
                                if ( *pNameBuffer == '\'' && *(pNameBuffer-1) != '\\' )
                                    bQuote = false;
                                else if( *pNameBuffer != '\\' || *(pNameBuffer+1) != '\'' )
                                    aDocURLBuffer.append(*pNameBuffer); // If escaped quote: only quote in the name
                                ++pNameBuffer;
                            }

                            if( *pNameBuffer == SC_COMPILER_FILE_TAB_SEP )  // after the last quote of the docname should be the # char
                            {
                                sal_Int32 nIndex = nNameLength - nLinkTabNameLength;
                                INetURLObject aINetURLObject(aDocURLBuffer);
                                if(aName.match( aLinkTabName, nIndex) &&
                                    (aName[nIndex - 1] == '#') && // before the table name should be the # char
                                    !aINetURLObject.HasError()) // the docname should be a valid URL
                                {
                                    aName = ScGlobal::GetDocTabName( m_pDocument->GetLinkDoc( i ), m_pDocument->GetLinkTab( i ) );
                                    m_pDocument->RenameTab(i, aName, true/*bExternalDocument*/);
                                }
                                // else;  nothing has to happen, because it is a user given name
                            }
                            // else;  nothing has to happen, because it is a user given name
                        }
                        // else;  nothing has to happen, because it is a user given name
                    }
                    // else;  nothing has to happen, because it is a user given name
                }
            }

            // #i94570# DataPilot table names have to be unique, or the tables can't be accessed by API.
            // If no name (or an invalid name, skipped in ScXMLDataPilotTableContext::EndElement) was set, create a new name.
            ScDPCollection* pDPCollection = m_pDocument->GetDPCollection();
            if ( pDPCollection )
            {
                size_t nDPCount = pDPCollection->GetCount();
                for (size_t nDP=0; nDP<nDPCount; ++nDP)
                {
                    ScDPObject& rDPObj = (*pDPCollection)[nDP];
                    if (rDPObj.GetName().isEmpty())
                        rDPObj.SetName( pDPCollection->CreateNewName() );
                }
            }
        }
    }
    else
        m_pDocument->SetInsertingFromOtherDoc( false );

    m_pDocument->SetImportingXML( false );
    m_pDocument->EnableExecuteLink( true );
    m_pDocument->EnableUndo( true );
    m_bIsEmpty = false;

    if (m_pModificator)
    {
        ScDocument::HardRecalcState eRecalcState = m_pDocument->GetHardRecalcState();
        // Temporarily set hard-recalc to prevent calling
        // ScFormulaCell::Notify() during destruction of the Modificator which
        // will set the cells dirty.
        if (eRecalcState == ScDocument::HardRecalcState::OFF)
            m_pDocument->SetHardRecalcState(ScDocument::HardRecalcState::TEMPORARY);
        m_pModificator.reset();
        m_pDocument->SetHardRecalcState(eRecalcState);
    }
    else
    {
        OSL_FAIL("The Modificator should exist");
    }

    m_pDocument->EnableIdle(true);
}

namespace {

class LoadMediumGuard
{
public:
    explicit LoadMediumGuard(ScDocument* pDoc) :
        mpDoc(pDoc)
    {
        mpDoc->SetLoadingMedium(true);
    }

    ~LoadMediumGuard()
    {
        mpDoc->SetLoadingMedium(false);
    }
private:
    ScDocument* mpDoc;
};

void processDataStream( ScDocShell& rShell, const sc::ImportPostProcessData& rData )
{
    if (!rData.mpDataStream)
        return;

    const sc::ImportPostProcessData::DataStream& r = *rData.mpDataStream;
    if (!r.maRange.IsValid())
        return;

    // Break the streamed range into the top range and the height limit.  A
    // height limit of 0 means unlimited i.e. the streamed data will go all
    // the way to the last row.

    ScRange aTopRange = r.maRange;
    aTopRange.aEnd.SetRow(aTopRange.aStart.Row());
    sal_Int32 nLimit = r.maRange.aEnd.Row() - r.maRange.aStart.Row() + 1;
    if (r.maRange.aEnd.Row() == rShell.GetDocument().MaxRow())
        // Unlimited range.
        nLimit = 0;

    sc::DataStream::MoveType eMove =
        r.meInsertPos == sc::ImportPostProcessData::DataStream::InsertTop ?
        sc::DataStream::MOVE_DOWN : sc::DataStream::RANGE_DOWN;

    sc::DataStream* pStrm = new sc::DataStream(&rShell, r.maURL, aTopRange, nLimit, eMove);
    pStrm->SetRefreshOnEmptyLine(r.mbRefreshOnEmpty);
    sc::DocumentLinkManager& rMgr = rShell.GetDocument().GetDocLinkManager();
    rMgr.setDataStream(pStrm);
}

class MessageWithCheck : public weld::MessageDialogController
{
private:
    std::unique_ptr<weld::CheckButton> m_xWarningOnBox;
public:
    MessageWithCheck(weld::Window *pParent, const OUString& rUIFile, const OUString&&nbsp;rDialogId)
        : MessageDialogController(pParent, rUIFile, rDialogId, u"ask"_ustr)
        , m_xWarningOnBox(m_xBuilder->weld_check_button(u"ask"_ustr))
    {
    }
    bool get_active() const { return m_xWarningOnBox->get_active(); }
    void hide_ask() const { m_xWarningOnBox->set_visible(false); };
};

#if HAVE_FEATURE_SCRIPTING
class VBAScriptListener : public ::cppu::WeakImplHelper< css::script::vba::XVBAScriptListener >
{
private:
    ScDocShell* m_pDocSh;
public:
    VBAScriptListener(ScDocShell* pDocSh) : m_pDocSh(pDocSh)
    {
    }

    // XVBAScriptListener
    virtual void SAL_CALL notifyVBAScriptEvent( const ::css::script::vba::VBAScriptEvent&&nbsp;aEvent ) override
    {
        if (aEvent.Identifier == script::vba::VBAScriptEventId::SCRIPT_STOPPED &&
            m_pDocSh->GetClipData().is())
        {
            m_pDocSh->SetClipData(uno::Reference<datatransfer::XTransferable2>());
        }
    }

    // XEventListener
    virtual void SAL_CALL disposing( const ::css::lang::EventObject& /*Source*/ ) override
    {
    }
};
#endif

}

bool ScDocShell::GetRecalcRowHeightsMode()
{
    const ScRecalcOptions nRecalcMode = static_cast<ScRecalcOptions>(
        officecfg::Office::Calc::Formula::Load::RecalcOptimalRowHeightMode::get());

    bool bHardRecalc = false;
    switch (nRecalcMode)
    {
        case RECALC_ASK:
        {
            if (m_pDocument->IsUserInteractionEnabled())
            {
                // Ask if the user wants to perform full re-calculation.
                MessageWithCheck aQueryBox(ScDocShell::GetActiveDialogParent(),
                                           u"modules/scalc/ui/recalcquerydialog.ui"_ustr,
                                           u"RecalcQueryDialog"_ustr);
                aQueryBox.set_primary_text(ScResId(STR_QUERY_OPT_ROW_HEIGHT_RECALC_ONLOAD));
                aQueryBox.set_default_response(RET_YES);

                if (officecfg::Office::Calc::Formula::Load::RecalcOptimalRowHeightMode::isReadOnly())
                    aQueryBox.hide_ask();

                bHardRecalc = aQueryBox.run() == RET_YES;

                if (aQueryBox.get_active())
                {
                    // Always perform selected action in the future.
                    std::shared_ptr<comphelper::ConfigurationChanges> batch(
                        comphelper::ConfigurationChanges::create());
                    officecfg::Office::Calc::Formula::Load::RecalcOptimalRowHeightMode::set(
                        bHardRecalc ? static_cast<sal_Int32>(RECALC_ALWAYS)
                                    : static_cast<sal_Int32>(RECALC_NEVER),
                        batch);

                    ScModule* mod = ScModule::get();
                    ScFormulaOptions aOpt = mod->GetFormulaOptions();
                    aOpt.SetReCalcOptiRowHeights(bHardRecalc ? RECALC_ALWAYS : RECALC_NEVER);
                    mod->SetFormulaOptions(aOpt);

                    batch->commit();
                }
            }
        }
        break;
        case RECALC_ALWAYS:
            bHardRecalc = true;
            break;
        case RECALC_NEVER:
            bHardRecalc = false;
            break;
        default:
            SAL_WARN("sc""unknown optimal row height recalc option!");
    }

    return bHardRecalc;
}

bool ScDocShell::LoadXML( SfxMedium* pLoadMedium, const css::uno::Reference< css::embed::XStorage >& xStor )
{
    LoadMediumGuard aLoadGuard(m_pDocument.get());

    //  MacroCallMode is no longer needed, state is kept in SfxObjectShell now

    // no Seek(0) here - always loading from storage, GetInStream must not be called

    BeforeXMLLoading();

    ScXMLImportWrapper aImport(*this, pLoadMedium, xStor);

    bool bRet = false;
    ErrCodeMsg nError = ERRCODE_NONE;
    m_pDocument->LockAdjustHeight();
    if (GetCreateMode() == SfxObjectCreateMode::ORGANIZER)
        bRet = aImport.Import(ImportFlags::Styles, nError);
    else
        bRet = aImport.Import(ImportFlags::All, nError);

    if ( nError )
        pLoadMedium->SetError(nError);

    processDataStream(*this, aImport.GetImportPostProcessData());

    //if the document was not generated by LibreOffice, do hard recalc in case some other document
    //generator saved cached formula results that differ from LibreOffice's calculated results or
    //did not use cached formula results.
    uno::Reference<document::XDocumentProperties> xDocProps = GetModel()->getDocumentProperties();

    ScRecalcOptions nRecalcMode =
        static_cast<ScRecalcOptions>(officecfg::Office::Calc::Formula::Load::ODFRecalcMode::get());

    bool bHardRecalc = false;
    if (nRecalcMode == RECALC_ASK)
    {
        OUString sProductName(utl::ConfigManager::getProductName());
        if (m_pDocument->IsUserInteractionEnabled() && xDocProps->getGenerator().indexOf(sProductName) == -1)
        {
            // Generator is not LibreOffice.  Ask if the user wants to perform
            // full re-calculation.
            MessageWithCheck aQueryBox(GetActiveDialogParent(),
                    u"modules/scalc/ui/recalcquerydialog.ui"_ustr, u"RecalcQueryDialog"_ustr);
            aQueryBox.set_primary_text(ScResId(STR_QUERY_FORMULA_RECALC_ONLOAD_ODS));
            aQueryBox.set_default_response(RET_YES);

            if ( officecfg::Office::Calc::Formula::Load::OOXMLRecalcMode::isReadOnly() )
                aQueryBox.hide_ask();

            bHardRecalc = aQueryBox.run() == RET_YES;

            if (aQueryBox.get_active())
            {
                // Always perform selected action in the future.
                std::shared_ptr<comphelper::ConfigurationChanges> batch(comphelper::ConfigurationChanges::create());
                officecfg::Office::Calc::Formula::Load::ODFRecalcMode::set(sal_Int32(0), batch);
                ScModule* mod = ScModule::get();
                ScFormulaOptions aOpt = mod->GetFormulaOptions();
                aOpt.SetODFRecalcOptions(bHardRecalc ? RECALC_ALWAYS : RECALC_NEVER);
                /* XXX  is this really supposed to set the ScModule options?
                 *      Not the ScDocShell options? */

                mod->SetFormulaOptions(aOpt);

                batch->commit();
            }
        }
    }
    else if (nRecalcMode == RECALC_ALWAYS)
        bHardRecalc = true;

    if (bHardRecalc)
        DoHardRecalc();
    else
    {
        // still need to recalc volatile formula cells.
        m_pDocument->Broadcast(ScHint(SfxHintId::ScDataChanged, BCA_BRDCST_ALWAYS));
    }

    AfterXMLLoading(bRet);

    m_pDocument->UnlockAdjustHeight();
    return bRet;
}

bool ScDocShell::SaveXML( SfxMedium* pSaveMedium, const css::uno::Reference< css::embed::XStorage >& xStor )
{
    m_pDocument->EnableIdle(false);

    ScXMLImportWrapper aImport(*this, pSaveMedium, xStor);
    bool bRet(false);
    if (GetCreateMode() != SfxObjectCreateMode::ORGANIZER)
        bRet = aImport.Export(false);
    else
        bRet = aImport.Export(true);

    m_pDocument->EnableIdle(true);

    return bRet;
}

bool ScDocShell::Load( SfxMedium& rMedium )
{
    LoadMediumGuard aLoadGuard(m_pDocument.get());
    ScRefreshTimerProtector aProt( m_pDocument->GetRefreshTimerControlAddress() );

    //  only the latin script language is loaded
    //  -> initialize the others from options (before loading)
    InitOptions(true);

    // If this is an ODF file being loaded, then by default, use legacy processing
    // (if required, it will be overridden in *::ReadUserDataSequence())
    if (IsOwnStorageFormat(rMedium))
    {
        if (ScDrawLayer* pDrawLayer = m_pDocument->GetDrawLayer())
        {
            pDrawLayer->SetCompatibilityFlag(SdrCompatibilityFlag::AnchoredTextOverflowLegacy,
                                             true); // for tdf#99729
            pDrawLayer->SetCompatibilityFlag(SdrCompatibilityFlag::LegacyFontwork,
                                             true); // for tdf#148000
        }
    }

    GetUndoManager()->Clear();

    bool bRet = SfxObjectShell::Load(rMedium);
    if (bRet)
    {
        SetInitialLinkUpdate(&rMedium);

        {
            //  prepare a valid document for XML filter
            //  (for ConvertFrom, InitNew is called before)
            m_pDocument->MakeTable(0);
            m_pDocument->GetStyleSheetPool()->CreateStandardStyles();
            m_pDocument->getCellAttributeHelper().UpdateAllStyleSheets(*m_pDocument);

            /* Create styles that are imported through Orcus */

            OUString aURL(u"$BRAND_BASE_DIR/" LIBO_SHARE_FOLDER "/calc/styles.xml"_ustr);
            rtl::Bootstrap::expandMacros(aURL);

            OUString aPath;
            osl::FileBase::getSystemPathFromFileURL(aURL, aPath);

            ScOrcusFilters* pOrcus = ScFormatFilter::Get().GetOrcusFilters();

            if (pOrcus)
            {
                pOrcus->importODS_Styles(*m_pDocument, aPath);
                m_pDocument->GetStyleSheetPool()->setAllParaStandard();
            }

            bRet = LoadXML( &rMedium, nullptr );
        }
    }

    if (!bRet && !rMedium.GetErrorIgnoreWarning())
        rMedium.SetError(SVSTREAM_FILEFORMAT_ERROR);

    if (rMedium.GetErrorIgnoreWarning())
        SetError(rMedium.GetErrorIgnoreWarning());

    InitItems();
    CalcOutputFactor();

    // invalidate eventually temporary table areas
    if ( bRet )
        m_pDocument->InvalidateTableArea();

    m_bIsEmpty = false;
    FinishedLoading();
    return bRet;
}

void ScDocShell::Notify( SfxBroadcaster&, const SfxHint& rHint )
{
    if (rHint.GetId() == SfxHintId::ScTables)
    {
        const ScTablesHint* pScHint = static_castconst ScTablesHint* >( &rHint );
        if (pScHint->GetTablesHintId() == SC_TAB_INSERTED)
        {
            uno::Reference< script::vba::XVBAEventProcessor > xVbaEvents = m_pDocument->GetVbaEventProcessor();
            if ( xVbaEvents.is() ) try
            {
                uno::Sequence< uno::Any > aArgs{ uno::Any(pScHint->GetTab1()) };
                xVbaEvents->processVbaEvent( script::vba::VBAEventId::WORKBOOK_NEWSHEET, aArgs );
            }
            catch( uno::Exception& )
            {
            }
        }
    }

    if ( auto pStyleSheetHint = dynamic_cast<const SfxStyleSheetHint*>(&rHint) ) // Template changed
        NotifyStyle( *pStyleSheetHint );
    else if ( rHint.GetId() == SfxHintId::ScAutoStyle )
    {
        auto pStlHint = static_cast<const ScAutoStyleHint*>(&rHint);
        //! direct call for AutoStyles

        //  this is called synchronously from ScInterpreter::ScStyle,
        //  modifying the document must be asynchronous
        //  (handled by AddInitial)

        const ScRange& aRange = pStlHint->GetRange();
        const OUString& aName1 = pStlHint->GetStyle1();
        const OUString& aName2 = pStlHint->GetStyle2();
        sal_uInt32 nTimeout = pStlHint->GetTimeout();

        if (!m_pAutoStyleList)
            m_pAutoStyleList.reset( new ScAutoStyleList(this) );
        m_pAutoStyleList->AddInitial( aRange, aName1, nTimeout, aName2 );
    }
    else if (rHint.GetId() == SfxHintId::ThisIsAnSfxEventHint)
    {
        switch (static_cast<const SfxEventHint&>(rHint).GetEventId())
        {
            case SfxEventHintId::LoadFinished:
                {
#if HAVE_FEATURE_MULTIUSER_ENVIRONMENT
                    // the readonly documents should not be opened in shared mode
                    if ( HasSharedXMLFlagSet() && !ScModule::get()->IsInSharedDocLoading() && !IsReadOnly() )
                    {
                        if ( SwitchToShared( truefalse ) )
                        {
                            ScViewData* pViewData = GetViewData();
                            ScTabView* pTabView = ( pViewData ? pViewData->GetView() : nullptr );
                            if ( pTabView )
                            {
                                pTabView->UpdateLayerLocks();
                            }
                        }
                        else
                        {
                            // switching to shared mode has failed, the document should be opened readonly
                            // TODO/LATER: And error message should be shown here probably
                            SetReadOnlyUI();
                        }
                    }
#endif
                }
                break;
            case SfxEventHintId::ViewCreated:
                {
 #if HAVE_FEATURE_SCRIPTING
                    uno::Reference<script::vba::XVBACompatibility> xVBACompat(GetBasicContainer(), uno::UNO_QUERY);
                    if ( !m_xVBAListener.is() && xVBACompat.is() )
                    {
                        m_xVBAListener.set(new VBAScriptListener(this));
                        xVBACompat->addVBAScriptListener(m_xVBAListener);
                    }
#endif

#if HAVE_FEATURE_MULTIUSER_ENVIRONMENT
                    if (ScModule* mod = ScModule::get(); IsDocShared() && !mod->IsInSharedDocLoading()
                         && !comphelper::LibreOfficeKit::isActive() )
                    {
                        ScAppOptions aAppOptions = mod->GetAppOptions();
                        if ( aAppOptions.GetShowSharedDocumentWarning() )
                        {
                            MessageWithCheck aWarningBox(ScDocShell::GetActiveDialogParent(),
                                    u"modules/scalc/ui/sharedwarningdialog.ui"_ustr, u"SharedWarningDialog"_ustr);
                            aWarningBox.run();

                            bool bChecked = aWarningBox.get_active();
                            if (bChecked)
                            {
                                aAppOptions.SetShowSharedDocumentWarning(false);
                                mod->SetAppOptions(aAppOptions);
                            }
                        }
                    }
#endif

                    ScViewData* pViewData = GetViewData();
                    SfxViewShell* pViewShell = pViewData ? pViewData->GetViewShell() : nullptr;
                    SfxViewFrame* pViewFrame = pViewShell ? &pViewShell->GetViewFrame() : nullptr;

                    try
                    {
                        const uno::Reference< uno::XComponentContext >& xContext(
                            comphelper::getProcessComponentContext() );
                        uno::Reference< lang::XMultiServiceFactory > xServiceManager(
                            xContext->getServiceManager(),
                            uno::UNO_QUERY_THROW );
                        uno::Reference< container::XContentEnumerationAccess > xEnumAccess( xServiceManager, uno::UNO_QUERY_THROW );
                        uno::Reference< container::XEnumeration> xEnum = xEnumAccess->createContentEnumeration(
                            u"com.sun.star.sheet.SpreadsheetDocumentJob"_ustr );
                        if ( xEnum.is() )
                        {
                            while ( xEnum->hasMoreElements() )
                            {
                                uno::Any aAny = xEnum->nextElement();
                                uno::Reference< lang::XSingleComponentFactory > xFactory;
                                aAny >>= xFactory;
                                if ( xFactory.is() )
                                {
                                    uno::Reference< task::XJob > xJob( xFactory->createInstanceWithContext( xContext ), uno::UNO_QUERY_THROW );
                                    SfxFrame* pFrame = ( pViewFrame ? &pViewFrame->GetFrame() : nullptr );
                                    uno::Reference< frame::XController > xController = ( pFrame ? pFrame->GetController() : nullptr );
                                    uno::Reference< sheet::XSpreadsheetView > xSpreadsheetView( xController, uno::UNO_QUERY_THROW );
                                    uno::Sequence< beans::NamedValue > aArgsForJob { { u"SpreadsheetView"_ustr, uno::Any( xSpreadsheetView ) } };
                                    xJob->execute( aArgsForJob );
                                }
                            }
                        }
                    }
                    catch ( uno::Exception & )
                    {
                    }

                    // Show delayed infobar entries
                    if (pViewFrame)
                    {
                        for (auto const& r : m_pImpl->mpDelayedInfobarEntry)
                        {
                            pViewFrame->AppendInfoBar(r.msId, r.msPrimaryMessage, r.msSecondaryMessage, r.maInfobarType, r.mbShowCloseButton);
                        }
                        m_pImpl->mpDelayedInfobarEntry.clear();
                    }
                }
                break;
            case SfxEventHintId::SaveDoc:
                {
#if HAVE_FEATURE_MULTIUSER_ENVIRONMENT
                    if (ScModule* mod = ScModule::get(); IsDocShared() && !mod->IsInSharedDocSaving())
                    {
                        bool bSuccess = false;
                        bool bRetry = true;
                        while ( bRetry )
                        {
                            bRetry = false;
                            uno::Reference< frame::XModel > xModel;
                            try
                            {
                                // load shared file
                                xModel.set( LoadSharedDocument(), uno::UNO_SET_THROW );
                                uno::Reference< util::XCloseable > xCloseable( xModel, uno::UNO_QUERY_THROW );

                                // check if shared flag is set in shared file
                                bool bShared = false;
                                ScModelObj* pDocObj = comphelper::getFromUnoTunnel<ScModelObj>( xModel );
                                ScDocShell* pSharedDocShell = ( pDocObj ? dynamic_cast< ScDocShell* >( pDocObj->GetObjectShell() ) : nullptr );
                                if ( pSharedDocShell )
                                {
                                    bShared = pSharedDocShell->HasSharedXMLFlagSet();
                                }

                                // #i87870# check if shared status was disabled and enabled again
                                bool bOwnEntry = false;
                                bool bEntriesNotAccessible = false;
                                try
                                {
                                    ::svt::ShareControlFile aControlFile( GetSharedFileURL() );
                                    bOwnEntry = aControlFile.HasOwnEntry();
                                }
                                catch ( uno::Exception& )
                                {
                                    bEntriesNotAccessible = true;
                                }

                                if ( bShared && bOwnEntry )
                                {
                                    uno::Reference< frame::XStorable > xStorable( xModel, uno::UNO_QUERY_THROW );

                                    if ( xStorable->isReadonly() )
                                    {
                                        xCloseable->close( true );

                                        OUString aUserName( ScResId( STR_UNKNOWN_USER ) );
                                        bool bNoLockAccess = false;
                                        try
                                        {
                                            ::svt::DocumentLockFile aLockFile( GetSharedFileURL() );
                                            LockFileEntry aData = aLockFile.GetLockData();
                                            if ( !aData[LockFileComponent::OOOUSERNAME].isEmpty() )
                                            {
                                                aUserName = aData[LockFileComponent::OOOUSERNAME];
                                            }
                                            else if ( !aData[LockFileComponent::SYSUSERNAME].isEmpty() )
                                            {
                                                aUserName = aData[LockFileComponent::SYSUSERNAME];
                                            }
                                        }
                                        catch ( uno::Exception& )
                                        {
                                            bNoLockAccess = true;
                                        }

                                        if ( bNoLockAccess )
                                        {
                                            // TODO/LATER: in future an error regarding impossibility to open file for writing could be shown
                                            ErrorHandler::HandleError( ERRCODE_IO_GENERAL );
                                        }
                                        else
                                        {
                                            OUString aMessage( ScResId( STR_FILE_LOCKED_SAVE_LATER ) );
                                            aMessage = aMessage.replaceFirst( "%1", aUserName );

                                            std::unique_ptr<weld::MessageDialog> xWarn(Application::CreateMessageDialog(GetActiveDialogParent(),
                                                                                       VclMessageType::Warning, VclButtonsType::NONE,
                                                                                       aMessage));
                                            xWarn->add_button(GetStandardText(StandardButtonType::Retry), RET_RETRY);
                                            xWarn->add_button(GetStandardText(StandardButtonType::Cancel), RET_CANCEL);
                                            xWarn->set_default_response(RET_RETRY);
                                            if (xWarn->run() == RET_RETRY)
                                            {
                                                bRetry = true;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        // merge changes from shared file into temp file
                                        bool bSaveToShared = false;
                                        if ( pSharedDocShell )
                                        {
                                            bSaveToShared = MergeSharedDocument( pSharedDocShell );
                                        }

                                        // close shared file
                                        xCloseable->close( true );

                                        // TODO: keep file lock on shared file

                                        // store to shared file
                                        if ( bSaveToShared )
                                        {
                                            bool bChangedViewSettings = false;
                                            ScChangeViewSettings* pChangeViewSet = m_pDocument->GetChangeViewSettings();
                                            if ( pChangeViewSet && pChangeViewSet->ShowChanges() )
                                            {
                                                pChangeViewSet->SetShowChanges( false );
                                                pChangeViewSet->SetShowAccepted( false );
                                                m_pDocument->SetChangeViewSettings( *pChangeViewSet );
                                                bChangedViewSettings = true;
                                            }

                                            // TODO/LATER: More entries from the MediaDescriptor might be interesting for the merge
                                            uno::Sequence< beans::PropertyValue > aValues{
                                                comphelper::makePropertyValue(
                                                    u"FilterName"_ustr,
                                                    GetMedium()->GetFilter()->GetFilterName())
                                            };

                                            const SfxStringItem* pPasswordItem = GetMedium()->GetItemSet().GetItem(SID_PASSWORD, false);
                                            if ( pPasswordItem && !pPasswordItem->GetValue().isEmpty() )
                                            {
                                                aValues.realloc( 2 );
                                                auto pValues = aValues.getArray();
                                                pValues[1].Name = "Password";
                                                pValues[1].Value <<= pPasswordItem->GetValue();
                                            }
                                            const SfxUnoAnyItem* pEncryptionItem = GetMedium()->GetItemSet().GetItem(SID_ENCRYPTIONDATA, false);
                                            if (pEncryptionItem)
                                            {
                                                aValues.realloc(aValues.getLength() + 1);
                                                auto pValues = aValues.getArray();
                                                pValues[aValues.getLength() - 1].Name = "EncryptionData";
                                                pValues[aValues.getLength() - 1].Value = pEncryptionItem->GetValue();
                                            }

                                            mod->SetInSharedDocSaving(true);
                                            GetModel()->storeToURL( GetSharedFileURL(), aValues );
                                            mod->SetInSharedDocSaving(false);

                                            if ( bChangedViewSettings )
                                            {
                                                pChangeViewSet->SetShowChanges( true );
                                                pChangeViewSet->SetShowAccepted( true );
                                                m_pDocument->SetChangeViewSettings( *pChangeViewSet );
                                            }
                                        }

                                        bSuccess = true;
                                        GetUndoManager()->Clear();
                                    }
                                }
                                else
                                {
                                    xCloseable->close( true );

                                    if ( bEntriesNotAccessible )
                                    {
                                        // TODO/LATER: in future an error regarding impossibility to write to share control file could be shown
                                        ErrorHandler::HandleError( ERRCODE_IO_GENERAL );
                                    }
                                    else
                                    {
                                        std::unique_ptr<weld::MessageDialog> xWarn(Application::CreateMessageDialog(GetActiveDialogParent(),
                                                                                   VclMessageType::Warning, VclButtonsType::Ok,
                                                                                   ScResId(STR_DOC_NOLONGERSHARED)));
                                        xWarn->run();

                                        SfxBindings* pBindings = GetViewBindings();
                                        if ( pBindings )
                                        {
                                            pBindings->ExecuteSynchron( SID_SAVEASDOC );
                                        }
                                    }
                                }
                            }
                            catch ( uno::Exception& )
                            {
                                TOOLS_WARN_EXCEPTION( "sc""SfxEventHintId::SaveDoc" );
                                mod->SetInSharedDocSaving(false);

                                try
                                {
                                    uno::Reference< util::XCloseable > xClose( xModel, uno::UNO_QUERY_THROW );
                                    xClose->close( true );
                                }
                                catch ( uno::Exception& )
                                {
                                }
                            }
                        }

                        if ( !bSuccess )
                            SetError(ERRCODE_IO_ABORT); // this error code will produce no error message, but will break the further saving process
                    }
#endif

                    if (m_pSheetSaveData)
                        m_pSheetSaveData->SetInSupportedSave(true);
                }
                break;
            case SfxEventHintId::SaveAsDoc:
                {
                    if ( GetDocument().GetExternalRefManager()->containsUnsavedReferences() )
                    {
                        std::unique_ptr<weld::MessageDialog> xWarn(Application::CreateMessageDialog(GetActiveDialogParent(),
                                                                   VclMessageType::Warning, VclButtonsType::YesNo,
                                                                   ScResId(STR_UNSAVED_EXT_REF)));
                        if (RET_NO == xWarn->run())
                        {
                            SetError(ERRCODE_IO_ABORT); // this error code will produce no error message, but will break the further saving process
                        }
                    }
                    [[fallthrough]];
                }
            case SfxEventHintId::SaveToDoc:
                // #i108978# If no event is sent before saving, there will also be no "...DONE" event,
                // and SAVE/SAVEAS can't be distinguished from SAVETO. So stream copying is only enabled
                // if there is a SAVE/SAVEAS/SAVETO event first.
                if (m_pSheetSaveData)
                    m_pSheetSaveData->SetInSupportedSave(true);
                break;
            case SfxEventHintId::SaveDocDone:
            case SfxEventHintId::SaveAsDocDone:
                {
                    // new positions are used after "save" and "save as", but not "save to"
                    UseSheetSaveEntries();      // use positions from saved file for next saving
                    [[fallthrough]];
                }
            case SfxEventHintId::SaveToDocDone:
                // only reset the flag, don't use the new positions
                if (m_pSheetSaveData)
                    m_pSheetSaveData->SetInSupportedSave(false);
                break;
            default:
                {
                }
                break;
        }
    }
    else if (rHint.GetId() == SfxHintId::TitleChanged) // Without parameter
    {
        m_pDocument->SetName( SfxShell::GetName() );
        //  RegisterNewTargetNames doesn't exist any longer
        SfxGetpApp()->Broadcast(SfxHint( SfxHintId::ScDocNameChanged )); // Navigator
    }
    else if (rHint.GetId() == SfxHintId::Deinitializing)
    {

#if HAVE_FEATURE_SCRIPTING
        uno::Reference<script::vba::XVBACompatibility> xVBACompat(GetBasicContainer(), uno::UNO_QUERY);
        if (m_xVBAListener.is() && xVBACompat.is())
        {
            xVBACompat->removeVBAScriptListener(m_xVBAListener);
        }
#endif

        if (m_pDocument->IsClipboardSource())
        {
            // Notes copied to the clipboard have a raw SdrCaptionObj pointer
            // copied from this document, forget it as it references this
            // document's drawing layer pages and what not, which otherwise when
            // pasting to another document after this document was destructed would
            // attempt to access non-existing data. Preserve the text data though.
            ScDocument* pClipDoc = ScModule::GetClipDoc();
            if (pClipDoc)
                pClipDoc->ClosingClipboardSource();
        }
    }

    if (rHint.GetId() != SfxHintId::ThisIsAnSfxEventHint)
        return;

    switch(static_cast<const SfxEventHint&>(rHint).GetEventId())
    {
       case SfxEventHintId::CreateDoc:
            {
                uno::Any aWorkbook;
                aWorkbook <<= mxAutomationWorkbookObject;
                uno::Sequence< uno::Any > aArgs{ aWorkbook };
                ScModule::get()->CallAutomationApplicationEventSinks(u"NewWorkbook"_ustr, aArgs);
            }
            break;
        case SfxEventHintId::OpenDoc:
            {
                uno::Any aWorkbook;
                aWorkbook <<= mxAutomationWorkbookObject;
                uno::Sequence< uno::Any > aArgs{ aWorkbook };
                ScModule::get()->CallAutomationApplicationEventSinks(u"WorkbookOpen"_ustr, aArgs);
            }
            break;
        default:
            break;
    }
}

// Load contents for organizer
bool ScDocShell::LoadFrom( SfxMedium& rMedium )
{
    LoadMediumGuard aLoadGuard(m_pDocument.get());
    ScRefreshTimerProtector aProt( m_pDocument->GetRefreshTimerControlAddress() );

    weld::WaitObject aWait( GetActiveDialogParent() );

    bool bRet = false;

    SetInitialLinkUpdate(&rMedium);

    //  until loading/saving only the styles in XML is implemented,
    //  load the whole file
    bRet = LoadXML( &rMedium, nullptr );
    InitItems();

    SfxObjectShell::LoadFrom( rMedium );

    return bRet;
}

static void lcl_parseHtmlFilterOption(const OUString& rOption, LanguageType& rLang, bool& rDateConvert, bool& rScientificConvert)
{
    OUStringBuffer aBuf;
    std::vector< OUString > aTokens;
    sal_Int32 n = rOption.getLength();
    const sal_Unicode* p = rOption.getStr();
    for (sal_Int32 i = 0; i < n; ++i)
    {
        const sal_Unicode c = p[i];
        if (c == ' ')
        {
            if (!aBuf.isEmpty())
                aTokens.push_back( aBuf.makeStringAndClear() );
        }
        else
            aBuf.append(c);
    }

    if (!aBuf.isEmpty())
        aTokens.push_back( aBuf.makeStringAndClear() );

    rLang = LanguageType( 0 );
    rDateConvert = false;

    if (!aTokens.empty())
        rLang = static_cast<LanguageType>(aTokens[0].toInt32());
    if (aTokens.size() > 1)
        rDateConvert = static_cast<bool>(aTokens[1].toInt32());
    if (aTokens.size() > 2)
        rScientificConvert = static_cast<bool>(aTokens[2].toInt32());
}

bool ScDocShell::ConvertFrom( SfxMedium& rMedium )
{
    LoadMediumGuard aLoadGuard(m_pDocument.get());

    bool bRet = false// sal_False means user quit!
                           // On error: Set error at stream

    ScRefreshTimerProtector aProt( m_pDocument->GetRefreshTimerControlAddress() );

    GetUndoManager()->Clear();

    // Set optimal col width after import?
    bool bSetColWidths = false;
    bool bSetSimpleTextColWidths = false;
    std::map<SCCOL, ScColWidthParam> aColWidthParam;
    ScRange aColWidthRange;
    // Set optimal row height after import?
    bool bSetRowHeights = false;

    vector<ScDocRowHeightUpdater::TabRanges> aRecalcRowRangesArray;

    //  All filters need the complete file in one piece (not asynchronously)
    //  So make sure that we transfer the whole file with CreateFileStream
    rMedium.GetPhysicalName();  //! Call CreateFileStream directly, if available

    SetInitialLinkUpdate(&rMedium);

    std::shared_ptr<const SfxFilter> pFilter = rMedium.GetFilter();
    if (pFilter)
    {
        OUString aFltName = pFilter->GetFilterName();

        bool bCalc3 = aFltName == "StarCalc 3.0";
        bool bCalc4 = aFltName == "StarCalc 4.0";
        if (!bCalc3 && !bCalc4)
            m_pDocument->SetInsertingFromOtherDoc( true );

        if (aFltName == pFilterXML)
            bRet = LoadXML( &rMedium, nullptr );
        else if (aFltName == pFilterLotus)
        {
            OUString sItStr;
            if ( const SfxStringItem* pOptionsItem = rMedium.GetItemSet().GetItemIfSet( SID_FILE_FILTEROPTIONS, true ) )
            {
                sItStr = pOptionsItem->GetValue();
            }

            if (sItStr.isEmpty())
            {
                //  default for lotus import (from API without options):
                //  IBM_437 encoding
                sItStr = ScGlobal::GetCharsetString( RTL_TEXTENCODING_IBM_437 );
            }

            ErrCode eError = ScFormatFilter::Get().ScImportLotus123( rMedium, *m_pDocument,
                                                ScGlobal::GetCharsetValue(sItStr));
            if (eError != ERRCODE_NONE)
            {
                if (!GetErrorIgnoreWarning())
                    SetError(eError);

                if( eError.IsWarning() )
                    bRet = true;
            }
            else
                bRet = true;
            bSetColWidths = true;
            bSetRowHeights = true;
        }
        else if ( aFltName == pFilterExcel4 || aFltName == pFilterExcel5 ||
                   aFltName == pFilterExcel95 || aFltName == pFilterExcel97 ||
                   aFltName == pFilterEx4Temp || aFltName == pFilterEx5Temp ||
                   aFltName == pFilterEx95Temp || aFltName == pFilterEx97Temp )
        {
            EXCIMPFORMAT eFormat = EIF_AUTO;
            if ( aFltName == pFilterExcel4 || aFltName == pFilterEx4Temp )
                eFormat = EIF_BIFF_LE4;
            else if ( aFltName == pFilterExcel5 || aFltName == pFilterExcel95 ||
                      aFltName == pFilterEx5Temp || aFltName == pFilterEx95Temp )
                eFormat = EIF_BIFF5;
            else if ( aFltName == pFilterExcel97 || aFltName == pFilterEx97Temp )
                eFormat = EIF_BIFF8;

            MakeDrawLayer(); //! In the filter
            CalcOutputFactor(); // prepare update of row height
            ErrCode eError = ScFormatFilter::Get().ScImportExcel( rMedium, m_pDocument.get(), eFormat );
            m_pDocument->UpdateFontCharSet();
            if ( m_pDocument->IsChartListenerCollectionNeedsUpdate() )
                m_pDocument->UpdateChartListenerCollection(); //! For all imports?

            // all graphics objects must have names
            m_pDocument->EnsureGraphicNames();

            if (eError == SCWARN_IMPORT_UNKNOWN_ENCRYPTION)
            {

                m_pImpl->mpDelayedInfobarEntry.push_back({ u"UnknownEncryption"_ustr, ScResId(STR_CONTENT_WITH_UNKNOWN_ENCRYPTION), u""_ustr, InfobarType::INFO, true });
                eError = ERRCODE_NONE;
            }

            if (eError != ERRCODE_NONE)
            {
                if (!GetErrorIgnoreWarning())
                    SetError(eError);
                if( eError.IsWarning() )
                    bRet = true;
            }
            else
                bRet = true;
        }
        else if (aFltName == SC_TEXT_CSV_FILTER_NAME)
        {
            ScAsciiOptions aOptions;
            bool bOptInit = false;

            if ( const SfxStringItem* pOptionsItem = rMedium.GetItemSet().GetItemIfSet( SID_FILE_FILTEROPTIONS ) )
            {
                aOptions.ReadFromString( pOptionsItem->GetValue(), rMedium.GetInStream() );
                bOptInit = true;
            }

            if ( !bOptInit )
            {
                //  default for ascii import (from API without options):
                //  UTF-8 encoding, comma, double quotes

                aOptions.SetCharSet(RTL_TEXTENCODING_UTF8);
                aOptions.SetFieldSeps( OUString(',') );
                aOptions.SetTextSep( '"' );
            }

            ErrCode eError = ERRCODE_NONE;
            bool bOverflowRow, bOverflowCol, bOverflowCell;
            bOverflowRow = bOverflowCol = bOverflowCell = false;

            if( ! rMedium.IsStorage() )
            {
                ScImportExport  aImpEx( *m_pDocument );
                aImpEx.SetExtOptions( aOptions );

                SvStream* pInStream = rMedium.GetInStream();
                if (pInStream)
                {
                    pInStream->SetStreamCharSet( aOptions.GetCharSet() );
                    pInStream->Seek( 0 );
                    bRet = aImpEx.ImportStream( *pInStream, rMedium.GetBaseURL(), SotClipboardFormatId::STRING );
                    eError = bRet ? ERRCODE_NONE : SCERR_IMPORT_CONNECT;
                    m_pDocument->StartAllListeners();
                    sc::SetFormulaDirtyContext aCxt;
                    m_pDocument->SetAllFormulasDirty(aCxt);

                    // tdf#82254 - check whether to include a byte-order-mark in the output
                    if (const bool bIncludeBOM = aImpEx.GetIncludeBOM())
                    {
                        aOptions.SetIncludeBOM(bIncludeBOM);
                        rMedium.GetItemSet().Put(
                            SfxStringItem(SID_FILE_FILTEROPTIONS, aOptions.WriteToString()));
                    }

                    // for mobile case, we use a copy of the original document and give it a temporary name before editing
                    // Therefore, the sheet name becomes ugly, long and nonsensical.
#if !(defined ANDROID)
                    // The same resulting name has to be handled in
                    // ScExternalRefCache::initializeDoc() and related, hence
                    // pass 'true' for RenameTab()'s bExternalDocument for a
                    // composed name so ValidTabName() will not be checked,
                    // which could veto the rename in case it contained
                    // characters that Excel does not handle. If we wanted to
                    // change that then it needed to be handled in all
                    // corresponding places of the external references
                    // manager/cache. Likely then we'd also need a method to
                    // compose a name excluding such characters.
                    m_pDocument->RenameTab( 0, INetURLObject( rMedium.GetName()).GetBase(), true/*bExternalDocument*/);
#endif
                    bOverflowRow = aImpEx.IsOverflowRow();
                    bOverflowCol = aImpEx.IsOverflowCol();
                    bOverflowCell = aImpEx.IsOverflowCell();
                }
                else
                {
                    OSL_FAIL( "No Stream" );
                }
            }

            if (eError != ERRCODE_NONE)
            {
                if (!GetErrorIgnoreWarning())
                    SetError(eError);
                if( eError.IsWarning() )
                    bRet = true;
            }
            else if (!GetErrorIgnoreWarning() && (bOverflowRow || bOverflowCol || bOverflowCell))
            {
                // precedence: row, column, cell
                ErrCode nWarn = (bOverflowRow ? SCWARN_IMPORT_ROW_OVERFLOW :
                        (bOverflowCol ? SCWARN_IMPORT_COLUMN_OVERFLOW :
                         SCWARN_IMPORT_CELL_OVERFLOW));
                SetError(nWarn);
            }
            bSetColWidths = true;
            bSetSimpleTextColWidths = true;
        }
        else if (aFltName == pFilterDBase)
        {
            OUString sItStr;
            if ( const SfxStringItem* pOptionsItem = rMedium.GetItemSet().GetItemIfSet( SID_FILE_FILTEROPTIONS ) )
            {
                sItStr = pOptionsItem->GetValue();
            }

            if (sItStr.isEmpty())
            {
                //  default for dBase import (from API without options):
                //  IBM_850 encoding

                sItStr = ScGlobal::GetCharsetString( RTL_TEXTENCODING_IBM_850 );
            }

            ScDocRowHeightUpdater::TabRanges aRecalcRanges(0, m_pDocument->MaxRow());
            ErrCode eError = DBaseImport( rMedium.GetPhysicalName(),
                    ScGlobal::GetCharsetValue(sItStr), aColWidthParam, aRecalcRanges.maRanges );
            aRecalcRowRangesArray.push_back(aRecalcRanges);

            if (eError != ERRCODE_NONE)
            {
                if (!GetErrorIgnoreWarning())
                    SetError(eError);
                if( eError.IsWarning() )
                    bRet = true;
            }
            else
                bRet = true;

            aColWidthRange.aStart.SetRow( 1 );  // Except for the column header
            bSetColWidths = true;
            bSetSimpleTextColWidths = true;
        }
        else if (aFltName == pFilterDif)
        {
            SvStream* pStream = rMedium.GetInStream();
            if (pStream)
            {
                ErrCode eError;
                OUString sItStr;
                if ( const SfxStringItem* pOptionsItem = rMedium.GetItemSet().GetItemIfSet( SID_FILE_FILTEROPTIONS ) )
                {
                    sItStr = pOptionsItem->GetValue();
                }

                if (sItStr.isEmpty())
                {
                    //  default for DIF import (from API without options):
                    //  ISO8859-1/MS_1252 encoding

                    sItStr = ScGlobal::GetCharsetString( RTL_TEXTENCODING_MS_1252 );
                }

                eError = ScFormatFilter::Get().ScImportDif( *pStream, m_pDocument.get(), ScAddress(0,0,0),
                                    ScGlobal::GetCharsetValue(sItStr));
                if (eError != ERRCODE_NONE)
                {
                    if (!GetErrorIgnoreWarning())
                        SetError(eError);

                    if( eError.IsWarning() )
                        bRet = true;
                }
                else
                    bRet = true;
            }
            bSetColWidths = true;
            bSetSimpleTextColWidths = true;
            bSetRowHeights = true;
        }
        else if (aFltName == pFilterSylk)
        {
            ErrCode eError = SCERR_IMPORT_UNKNOWN;
            bool bOverflowRow, bOverflowCol, bOverflowCell;
            bOverflowRow = bOverflowCol = bOverflowCell = false;
            if( !rMedium.IsStorage() )
            {
                ScImportExport aImpEx( *m_pDocument );

                SvStream* pInStream = rMedium.GetInStream();
                if (pInStream)
                {
                    pInStream->Seek( 0 );
                    bRet = aImpEx.ImportStream( *pInStream, rMedium.GetBaseURL(), SotClipboardFormatId::SYLK );
                    eError = bRet ? ERRCODE_NONE : SCERR_IMPORT_UNKNOWN;
                    m_pDocument->StartAllListeners();
                    sc::SetFormulaDirtyContext aCxt;
                    m_pDocument->SetAllFormulasDirty(aCxt);

                    bOverflowRow = aImpEx.IsOverflowRow();
                    bOverflowCol = aImpEx.IsOverflowCol();
                    bOverflowCell = aImpEx.IsOverflowCell();
                }
                else
                {
                    OSL_FAIL( "No Stream" );
                }
            }

            if (eError != ERRCODE_NONE)
            {
                if (!GetErrorIgnoreWarning())
                    SetError(eError);
                if( eError.IsWarning() )
                    bRet = true;
            }
            else if (!GetErrorIgnoreWarning() && (bOverflowRow || bOverflowCol || bOverflowCell))
            {
                // precedence: row, column, cell
                ErrCode nWarn = (bOverflowRow ? SCWARN_IMPORT_ROW_OVERFLOW :
                        (bOverflowCol ? SCWARN_IMPORT_COLUMN_OVERFLOW :
                         SCWARN_IMPORT_CELL_OVERFLOW));
                SetError(nWarn);
            }
            bSetColWidths = true;
            bSetSimpleTextColWidths = true;
            bSetRowHeights = true;
        }
        else if (aFltName == pFilterQPro6)
        {
            ErrCode eError = ScFormatFilter::Get().ScImportQuattroPro(rMedium.GetInStream(), *m_pDocument);
            if (eError != ERRCODE_NONE)
            {
                if (!GetErrorIgnoreWarning())
                    SetError(eError);
                if( eError.IsWarning() )
                    bRet = true;
            }
            else
                bRet = true;
            // TODO: Filter should set column widths. Not doing it here, it may
            // result in very narrow or wide columns, depending on content.
            // Setting row heights makes cells with font size attribution or
            // wrapping enabled look nicer...
            bSetRowHeights = true;
        }
        else if (aFltName == pFilterRtf)
        {
            ErrCode eError = SCERR_IMPORT_UNKNOWN;
            if( !rMedium.IsStorage() )
            {
                SvStream* pInStream = rMedium.GetInStream();
                if (pInStream)
                {
                    pInStream->Seek( 0 );
                    ScRange aRange;
--> --------------------

--> maximum size reached

--> --------------------

Messung V0.5
C=92 H=96 G=93

¤ Dauer der Verarbeitung: 0.21 Sekunden  ¤

*© Formatika GbR, Deutschland






Wurzel

Suchen

Beweissystem der NASA

Beweissystem Isabelle

NIST Cobol Testsuite

Cephes Mathematical Library

Wiener Entwicklungsmethode

Haftungshinweis

Die Informationen auf dieser Webseite wurden nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit, noch Qualität der bereit gestellten Informationen zugesichert.

Bemerkung:

Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.