Related: tdf#142635 Make ScDocShell reference ScDocument by shared_ptr

Required for eventual sharing of the document between the shell
and other pieces having different lifetime, as required to fix
tdf#142635.

Change-Id: I9e69bd2e3b57d7712526f51161e7e725d4af8068
Reviewed-on: https://gerrit.libreoffice.org/c/core/+/134383
Tested-by: Mike Kaganski <mike.kaganski@collabora.com>
Reviewed-by: Mike Kaganski <mike.kaganski@collabora.com>
diff --git a/sc/source/ui/docshell/docsh.cxx b/sc/source/ui/docshell/docsh.cxx
index 159520c..dd57fc6 100644
--- a/sc/source/ui/docshell/docsh.cxx
+++ b/sc/source/ui/docshell/docsh.cxx
@@ -205,7 +205,7 @@ void ScDocShell::FillClass( SvGlobalName* pClassName,

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

void ScDocShell::DoEnterHandler()
@@ -234,16 +234,16 @@ HiddenInformation ScDocShell::GetHiddenInformationState( HiddenInformation nStat

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

@@ -256,17 +256,17 @@ HiddenInformation ScDocShell::GetHiddenInformationState( HiddenInformation nStat

void ScDocShell::BeforeXMLLoading()
{
    m_aDocument.EnableIdle(false);
    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_aDocument.SetImportingXML( true );
    m_aDocument.EnableExecuteLink( false );   // #i101304# to be safe, prevent nested loading from external references
    m_aDocument.EnableUndo( false );
    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_aDocument.SetInsertingFromOtherDoc( true );
    m_pDocument->SetInsertingFromOtherDoc( true );
}

void ScDocShell::AfterXMLLoading(bool bRet)
@@ -275,22 +275,22 @@ void ScDocShell::AfterXMLLoading(bool bRet)
    {
        UpdateLinks();
        // don't prevent establishing of listeners anymore
        m_aDocument.SetInsertingFromOtherDoc( false );
        m_pDocument->SetInsertingFromOtherDoc( false );
        if ( bRet )
        {
            ScChartListenerCollection* pChartListener = m_aDocument.GetChartListenerCollection();
            ScChartListenerCollection* pChartListener = m_pDocument->GetChartListenerCollection();
            if (pChartListener)
                pChartListener->UpdateDirtyCharts();

            // #95582#; set the table names of linked tables to the new path
            SCTAB nTabCount = m_aDocument.GetTableCount();
            SCTAB nTabCount = m_pDocument->GetTableCount();
            for (SCTAB i = 0; i < nTabCount; ++i)
            {
                if (m_aDocument.IsLinked( i ))
                if (m_pDocument->IsLinked( i ))
                {
                    OUString aName;
                    m_aDocument.GetName(i, aName);
                    OUString aLinkTabName = m_aDocument.GetLinkTab(i);
                    m_pDocument->GetName(i, aName);
                    OUString aLinkTabName = m_pDocument->GetLinkTab(i);
                    sal_Int32 nLinkTabNameLength = aLinkTabName.getLength();
                    sal_Int32 nNameLength = aName.getLength();
                    if (nLinkTabNameLength < nNameLength)
@@ -321,8 +321,8 @@ void ScDocShell::AfterXMLLoading(bool bRet)
                                    (aName[nIndex - 1] == '#') && // before the table name should be the # char
                                    !aINetURLObject.HasError()) // the docname should be a valid URL
                                {
                                    aName = ScGlobal::GetDocTabName( m_aDocument.GetLinkDoc( i ), m_aDocument.GetLinkTab( i ) );
                                    m_aDocument.RenameTab(i, aName, true/*bExternalDocument*/);
                                    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
                            }
@@ -336,7 +336,7 @@ void ScDocShell::AfterXMLLoading(bool bRet)

            // #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_aDocument.GetDPCollection();
            ScDPCollection* pDPCollection = m_pDocument->GetDPCollection();
            if ( pDPCollection )
            {
                size_t nDPCount = pDPCollection->GetCount();
@@ -350,30 +350,30 @@ void ScDocShell::AfterXMLLoading(bool bRet)
        }
    }
    else
        m_aDocument.SetInsertingFromOtherDoc( false );
        m_pDocument->SetInsertingFromOtherDoc( false );

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

    if (m_pModificator)
    {
        ScDocument::HardRecalcState eRecalcState = m_aDocument.GetHardRecalcState();
        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_aDocument.SetHardRecalcState(ScDocument::HardRecalcState::TEMPORARY);
            m_pDocument->SetHardRecalcState(ScDocument::HardRecalcState::TEMPORARY);
        m_pModificator.reset();
        m_aDocument.SetHardRecalcState(eRecalcState);
        m_pDocument->SetHardRecalcState(eRecalcState);
    }
    else
    {
        OSL_FAIL("The Modificator should exist");
    }

    m_aDocument.EnableIdle(true);
    m_pDocument->EnableIdle(true);
}

namespace {
@@ -470,7 +470,7 @@ public:

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

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

@@ -482,7 +482,7 @@ bool ScDocShell::LoadXML( SfxMedium* pLoadMedium, const css::uno::Reference< css

    bool bRet = false;
    ErrCode nError = ERRCODE_NONE;
    m_aDocument.LockAdjustHeight();
    m_pDocument->LockAdjustHeight();
    if (GetCreateMode() == SfxObjectCreateMode::ORGANIZER)
        bRet = aImport.Import(ImportFlags::Styles, nError);
    else
@@ -506,7 +506,7 @@ bool ScDocShell::LoadXML( SfxMedium* pLoadMedium, const css::uno::Reference< css
    if (nRecalcMode == RECALC_ASK)
    {
        OUString sProductName(utl::ConfigManager::getProductName());
        if (m_aDocument.IsUserInteractionEnabled() && xDocProps->getGenerator().indexOf(sProductName) == -1)
        if (m_pDocument->IsUserInteractionEnabled() && xDocProps->getGenerator().indexOf(sProductName) == -1)
        {
            // Generator is not LibreOffice.  Ask if the user wants to perform
            // full re-calculation.
@@ -543,18 +543,18 @@ bool ScDocShell::LoadXML( SfxMedium* pLoadMedium, const css::uno::Reference< css
    else
    {
        // still need to recalc volatile formula cells.
        m_aDocument.Broadcast(ScHint(SfxHintId::ScDataChanged, BCA_BRDCST_ALWAYS));
        m_pDocument->Broadcast(ScHint(SfxHintId::ScDataChanged, BCA_BRDCST_ALWAYS));
    }

    AfterXMLLoading(bRet);

    m_aDocument.UnlockAdjustHeight();
    m_pDocument->UnlockAdjustHeight();
    return bRet;
}

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

    ScXMLImportWrapper aImport(*this, pSaveMedium, xStor);
    bool bRet(false);
@@ -563,15 +563,15 @@ bool ScDocShell::SaveXML( SfxMedium* pSaveMedium, const css::uno::Reference< css
    else
        bRet = aImport.Export(true);

    m_aDocument.EnableIdle(true);
    m_pDocument->EnableIdle(true);

    return bRet;
}

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

    //  only the latin script language is loaded
    //  -> initialize the others from options (before loading)
@@ -581,8 +581,8 @@ bool ScDocShell::Load( SfxMedium& rMedium )
    // for tdf#99729 (if required, it will be overridden in *::ReadUserDataSequence())
    if (IsOwnStorageFormat(rMedium))
    {
        if (m_aDocument.GetDrawLayer())
            m_aDocument.GetDrawLayer()->SetAnchoredTextOverflowLegacy(true);
        if (m_pDocument->GetDrawLayer())
            m_pDocument->GetDrawLayer()->SetAnchoredTextOverflowLegacy(true);
    }

    GetUndoManager()->Clear();
@@ -595,9 +595,9 @@ bool ScDocShell::Load( SfxMedium& rMedium )
        {
            //  prepare a valid document for XML filter
            //  (for ConvertFrom, InitNew is called before)
            m_aDocument.MakeTable(0);
            m_aDocument.GetStyleSheetPool()->CreateStandardStyles();
            m_aDocument.UpdStlShtPtrsFrmNms();
            m_pDocument->MakeTable(0);
            m_pDocument->GetStyleSheetPool()->CreateStandardStyles();
            m_pDocument->UpdStlShtPtrsFrmNms();

            if (!m_bUcalcTest)
            {
@@ -613,8 +613,8 @@ bool ScDocShell::Load( SfxMedium& rMedium )

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

@@ -633,7 +633,7 @@ bool ScDocShell::Load( SfxMedium& rMedium )

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

    m_bIsEmpty = false;
    FinishedLoading();
@@ -647,7 +647,7 @@ void ScDocShell::Notify( SfxBroadcaster&, const SfxHint& rHint )
    {
        if (pScHint->GetTablesHintId() == SC_TAB_INSERTED)
        {
            uno::Reference< script::vba::XVBAEventProcessor > xVbaEvents = m_aDocument.GetVbaEventProcessor();
            uno::Reference< script::vba::XVBAEventProcessor > xVbaEvents = m_pDocument->GetVbaEventProcessor();
            if ( xVbaEvents.is() ) try
            {
                uno::Sequence< uno::Any > aArgs{ uno::Any(pScHint->GetTab1()) };
@@ -883,12 +883,12 @@ void ScDocShell::Notify( SfxBroadcaster&, const SfxHint& rHint )
                                        if ( bSaveToShared )
                                        {
                                            bool bChangedViewSettings = false;
                                            ScChangeViewSettings* pChangeViewSet = m_aDocument.GetChangeViewSettings();
                                            ScChangeViewSettings* pChangeViewSet = m_pDocument->GetChangeViewSettings();
                                            if ( pChangeViewSet && pChangeViewSet->ShowChanges() )
                                            {
                                                pChangeViewSet->SetShowChanges( false );
                                                pChangeViewSet->SetShowAccepted( false );
                                                m_aDocument.SetChangeViewSettings( *pChangeViewSet );
                                                m_pDocument->SetChangeViewSettings( *pChangeViewSet );
                                                bChangedViewSettings = true;
                                            }

@@ -917,7 +917,7 @@ void ScDocShell::Notify( SfxBroadcaster&, const SfxHint& rHint )
                                            {
                                                pChangeViewSet->SetShowChanges( true );
                                                pChangeViewSet->SetShowAccepted( true );
                                                m_aDocument.SetChangeViewSettings( *pChangeViewSet );
                                                m_pDocument->SetChangeViewSettings( *pChangeViewSet );
                                            }
                                        }

@@ -1015,7 +1015,7 @@ void ScDocShell::Notify( SfxBroadcaster&, const SfxHint& rHint )
    }
    else if (rHint.GetId() == SfxHintId::TitleChanged) // Without parameter
    {
        m_aDocument.SetName( SfxShell::GetName() );
        m_pDocument->SetName( SfxShell::GetName() );
        //  RegisterNewTargetNames doesn't exist any longer
        SfxGetpApp()->Broadcast(SfxHint( SfxHintId::ScDocNameChanged )); // Navigator
    }
@@ -1030,7 +1030,7 @@ void ScDocShell::Notify( SfxBroadcaster&, const SfxHint& rHint )
        }
#endif

        if (m_aDocument.IsClipboardSource())
        if (m_pDocument->IsClipboardSource())
        {
            // Notes copied to the clipboard have a raw SdrCaptionObj pointer
            // copied from this document, forget it as it references this
@@ -1073,8 +1073,8 @@ void ScDocShell::Notify( SfxBroadcaster&, const SfxHint& rHint )
// Load contents for organizer
bool ScDocShell::LoadFrom( SfxMedium& rMedium )
{
    LoadMediumGuard aLoadGuard(&m_aDocument);
    ScRefreshTimerProtector aProt( m_aDocument.GetRefreshTimerControlAddress() );
    LoadMediumGuard aLoadGuard(m_pDocument.get());
    ScRefreshTimerProtector aProt( m_pDocument->GetRefreshTimerControlAddress() );

    weld::WaitObject aWait( GetActiveDialogParent() );

@@ -1124,12 +1124,12 @@ static void lcl_parseHtmlFilterOption(const OUString& rOption, LanguageType& rLa

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

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

    ScRefreshTimerProtector aProt( m_aDocument.GetRefreshTimerControlAddress() );
    ScRefreshTimerProtector aProt( m_pDocument->GetRefreshTimerControlAddress() );

    GetUndoManager()->Clear();

@@ -1157,7 +1157,7 @@ bool ScDocShell::ConvertFrom( SfxMedium& rMedium )
        bool bCalc3 = aFltName == "StarCalc 3.0";
        bool bCalc4 = aFltName == "StarCalc 4.0";
        if (!bCalc3 && !bCalc4)
            m_aDocument.SetInsertingFromOtherDoc( true );
            m_pDocument->SetInsertingFromOtherDoc( true );

        if (aFltName == pFilterXML)
            bRet = LoadXML( &rMedium, nullptr );
@@ -1179,7 +1179,7 @@ bool ScDocShell::ConvertFrom( SfxMedium& rMedium )
                sItStr = ScGlobal::GetCharsetString( RTL_TEXTENCODING_IBM_437 );
            }

            ErrCode eError = ScFormatFilter::Get().ScImportLotus123( rMedium, m_aDocument,
            ErrCode eError = ScFormatFilter::Get().ScImportLotus123( rMedium, *m_pDocument,
                                                ScGlobal::GetCharsetValue(sItStr));
            if (eError != ERRCODE_NONE)
            {
@@ -1210,13 +1210,13 @@ bool ScDocShell::ConvertFrom( SfxMedium& rMedium )

            MakeDrawLayer(); //! In the filter
            CalcOutputFactor(); // prepare update of row height
            ErrCode eError = ScFormatFilter::Get().ScImportExcel( rMedium, &m_aDocument, eFormat );
            m_aDocument.UpdateFontCharSet();
            if ( m_aDocument.IsChartListenerCollectionNeedsUpdate() )
                m_aDocument.UpdateChartListenerCollection(); //! For all imports?
            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_aDocument.EnsureGraphicNames();
            m_pDocument->EnsureGraphicNames();

            if (eError != ERRCODE_NONE)
            {
@@ -1234,7 +1234,7 @@ bool ScDocShell::ConvertFrom( SfxMedium& rMedium )
            if (!pOrcus)
                return false;

            bRet = pOrcus->importGnumeric(m_aDocument, rMedium);
            bRet = pOrcus->importGnumeric(*m_pDocument, rMedium);
        }
        else if (aFltName == "MS Excel 2003 XML Orcus")
        {
@@ -1242,7 +1242,7 @@ bool ScDocShell::ConvertFrom( SfxMedium& rMedium )
            if (!pOrcus)
                return false;

            bRet = pOrcus->importExcel2003XML(m_aDocument, rMedium);
            bRet = pOrcus->importExcel2003XML(*m_pDocument, rMedium);
        }
        else if (aFltName == SC_TEXT_CSV_FILTER_NAME)
        {
@@ -1274,7 +1274,7 @@ bool ScDocShell::ConvertFrom( SfxMedium& rMedium )

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

                SvStream* pInStream = rMedium.GetInStream();
@@ -1284,9 +1284,9 @@ bool ScDocShell::ConvertFrom( SfxMedium& rMedium )
                    pInStream->Seek( 0 );
                    bRet = aImpEx.ImportStream( *pInStream, rMedium.GetBaseURL(), SotClipboardFormatId::STRING );
                    eError = bRet ? ERRCODE_NONE : SCERR_IMPORT_CONNECT;
                    m_aDocument.StartAllListeners();
                    m_pDocument->StartAllListeners();
                    sc::SetFormulaDirtyContext aCxt;
                    m_aDocument.SetAllFormulasDirty(aCxt);
                    m_pDocument->SetAllFormulasDirty(aCxt);

                    bool bIsMobile = comphelper::LibreOfficeKit::isActive() && SfxViewShell::Current()
                        && SfxViewShell::Current()->isLOKMobilePhone();
@@ -1303,7 +1303,7 @@ bool ScDocShell::ConvertFrom( SfxMedium& rMedium )
                        // corresponding places of the external references
                        // manager/cache. Likely then we'd also need a method to
                        // compose a name excluding such characters.
                        m_aDocument.RenameTab( 0, INetURLObject( rMedium.GetName()).GetBase(), true/*bExternalDocument*/);
                        m_pDocument->RenameTab( 0, INetURLObject( rMedium.GetName()).GetBase(), true/*bExternalDocument*/);

                    bOverflowRow = aImpEx.IsOverflowRow();
                    bOverflowCol = aImpEx.IsOverflowCol();
@@ -1352,7 +1352,7 @@ bool ScDocShell::ConvertFrom( SfxMedium& rMedium )
                sItStr = ScGlobal::GetCharsetString( RTL_TEXTENCODING_IBM_850 );
            }

            ScDocRowHeightUpdater::TabRanges aRecalcRanges(0, m_aDocument.MaxRow());
            ScDocRowHeightUpdater::TabRanges aRecalcRanges(0, m_pDocument->MaxRow());
            ErrCode eError = DBaseImport( rMedium.GetPhysicalName(),
                    ScGlobal::GetCharsetValue(sItStr), aColWidthParam, aRecalcRanges.maRanges );
            aRecalcRowRangesArray.push_back(aRecalcRanges);
@@ -1394,7 +1394,7 @@ bool ScDocShell::ConvertFrom( SfxMedium& rMedium )
                    sItStr = ScGlobal::GetCharsetString( RTL_TEXTENCODING_MS_1252 );
                }

                eError = ScFormatFilter::Get().ScImportDif( *pStream, &m_aDocument, ScAddress(0,0,0),
                eError = ScFormatFilter::Get().ScImportDif( *pStream, m_pDocument.get(), ScAddress(0,0,0),
                                    ScGlobal::GetCharsetValue(sItStr));
                if (eError != ERRCODE_NONE)
                {
@@ -1418,7 +1418,7 @@ bool ScDocShell::ConvertFrom( SfxMedium& rMedium )
            bOverflowRow = bOverflowCol = bOverflowCell = false;
            if( !rMedium.IsStorage() )
            {
                ScImportExport aImpEx( m_aDocument );
                ScImportExport aImpEx( *m_pDocument );

                SvStream* pInStream = rMedium.GetInStream();
                if (pInStream)
@@ -1426,9 +1426,9 @@ bool ScDocShell::ConvertFrom( SfxMedium& rMedium )
                    pInStream->Seek( 0 );
                    bRet = aImpEx.ImportStream( *pInStream, rMedium.GetBaseURL(), SotClipboardFormatId::SYLK );
                    eError = bRet ? ERRCODE_NONE : SCERR_IMPORT_UNKNOWN;
                    m_aDocument.StartAllListeners();
                    m_pDocument->StartAllListeners();
                    sc::SetFormulaDirtyContext aCxt;
                    m_aDocument.SetAllFormulasDirty(aCxt);
                    m_pDocument->SetAllFormulasDirty(aCxt);

                    bOverflowRow = aImpEx.IsOverflowRow();
                    bOverflowCol = aImpEx.IsOverflowCol();
@@ -1461,7 +1461,7 @@ bool ScDocShell::ConvertFrom( SfxMedium& rMedium )
        }
        else if (aFltName == pFilterQPro6)
        {
            ErrCode eError = ScFormatFilter::Get().ScImportQuattroPro(rMedium.GetInStream(), m_aDocument);
            ErrCode eError = ScFormatFilter::Get().ScImportQuattroPro(rMedium.GetInStream(), *m_pDocument);
            if (eError != ERRCODE_NONE)
            {
                if (!GetError())
@@ -1487,7 +1487,7 @@ bool ScDocShell::ConvertFrom( SfxMedium& rMedium )
                {
                    pInStream->Seek( 0 );
                    ScRange aRange;
                    eError = ScFormatFilter::Get().ScImportRTF( *pInStream, rMedium.GetBaseURL(), &m_aDocument, aRange );
                    eError = ScFormatFilter::Get().ScImportRTF( *pInStream, rMedium.GetBaseURL(), m_pDocument.get(), aRange );
                    if (eError != ERRCODE_NONE)
                    {
                        if (!GetError())
@@ -1498,9 +1498,9 @@ bool ScDocShell::ConvertFrom( SfxMedium& rMedium )
                    }
                    else
                        bRet = true;
                    m_aDocument.StartAllListeners();
                    m_pDocument->StartAllListeners();
                    sc::SetFormulaDirtyContext aCxt;
                    m_aDocument.SetAllFormulasDirty(aCxt);
                    m_pDocument->SetAllFormulasDirty(aCxt);
                    bSetColWidths = true;
                    bSetRowHeights = true;
                }
@@ -1543,7 +1543,7 @@ bool ScDocShell::ConvertFrom( SfxMedium& rMedium )
                    // HTML does its own ColWidth/RowHeight
                    CalcOutputFactor();
                    SvNumberFormatter aNumFormatter( comphelper::getProcessComponentContext(), eLang);
                    eError = ScFormatFilter::Get().ScImportHTML( *pInStream, rMedium.GetBaseURL(), &m_aDocument, aRange,
                    eError = ScFormatFilter::Get().ScImportHTML( *pInStream, rMedium.GetBaseURL(), m_pDocument.get(), aRange,
                                            GetOutputFactor(), !bWebQuery, &aNumFormatter, bDateConvert );
                    if (eError != ERRCODE_NONE)
                    {
@@ -1555,10 +1555,10 @@ bool ScDocShell::ConvertFrom( SfxMedium& rMedium )
                    }
                    else
                        bRet = true;
                    m_aDocument.StartAllListeners();
                    m_pDocument->StartAllListeners();

                    sc::SetFormulaDirtyContext aCxt;
                    m_aDocument.SetAllFormulasDirty(aCxt);
                    m_pDocument->SetAllFormulasDirty(aCxt);
                }
                else
                {
@@ -1584,7 +1584,7 @@ bool ScDocShell::ConvertFrom( SfxMedium& rMedium )
        }

        if (!bCalc3)
            m_aDocument.SetInsertingFromOtherDoc( false );
            m_pDocument->SetInsertingFromOtherDoc( false );
    }
    else
    {
@@ -1600,15 +1600,15 @@ bool ScDocShell::ConvertFrom( SfxMedium& rMedium )
        double nPPTY = ScGlobal::nScreenPPTY * static_cast<double>(aZoom);
        ScopedVclPtrInstance< VirtualDevice > pVirtDev;
        //  all sheets (for Excel import)
        SCTAB nTabCount = m_aDocument.GetTableCount();
        SCTAB nTabCount = m_pDocument->GetTableCount();
        for (SCTAB nTab=0; nTab<nTabCount; nTab++)
        {
            SCCOL nEndCol;
            SCROW nEndRow;
            m_aDocument.GetCellArea( nTab, nEndCol, nEndRow );
            m_pDocument->GetCellArea( nTab, nEndCol, nEndRow );
            aColWidthRange.aEnd.SetCol( nEndCol );
            aColWidthRange.aEnd.SetRow( nEndRow );
            ScMarkData aMark(m_aDocument.GetSheetLimits());
            ScMarkData aMark(m_pDocument->GetSheetLimits());
            aMark.SetMarkArea( aColWidthRange );
            aMark.MarkToMulti();

@@ -1620,10 +1620,10 @@ bool ScDocShell::ConvertFrom( SfxMedium& rMedium )
                    if (!bSetSimpleTextColWidths)
                        aColWidthParam[nCol].mbSimpleText = false;

                    sal_uInt16 nWidth = m_aDocument.GetOptimalColWidth(
                    sal_uInt16 nWidth = m_pDocument->GetOptimalColWidth(
                        nCol, nTab, pVirtDev, nPPTX, nPPTY, aZoom, aZoom, false, &aMark,
                        &aColWidthParam[nCol] );
                    m_aDocument.SetColWidth( nCol, nTab,
                    m_pDocument->SetColWidth( nCol, nTab,
                        nWidth + static_cast<sal_uInt16>(ScGlobal::nLastColWidthExtra) );
                }
            }
@@ -1633,14 +1633,14 @@ bool ScDocShell::ConvertFrom( SfxMedium& rMedium )
        {
            // Update all rows in all tables.
            ScSizeDeviceProvider aProv(this);
            ScDocRowHeightUpdater aUpdater(m_aDocument, aProv.GetDevice(), aProv.GetPPTX(), aProv.GetPPTY(), nullptr);
            ScDocRowHeightUpdater aUpdater(*m_pDocument, aProv.GetDevice(), aProv.GetPPTX(), aProv.GetPPTY(), nullptr);
            aUpdater.update();
        }
        else if (!aRecalcRowRangesArray.empty())
        {
            // Update only specified row ranges for better performance.
            ScSizeDeviceProvider aProv(this);
            ScDocRowHeightUpdater aUpdater(m_aDocument, aProv.GetDevice(), aProv.GetPPTX(), aProv.GetPPTY(), &aRecalcRowRangesArray);
            ScDocRowHeightUpdater aUpdater(*m_pDocument, aProv.GetDevice(), aProv.GetPPTX(), aProv.GetPPTY(), &aRecalcRowRangesArray);
            aUpdater.update();
        }
    }
@@ -1648,7 +1648,7 @@ bool ScDocShell::ConvertFrom( SfxMedium& rMedium )

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

    m_bIsEmpty = false;

@@ -1670,22 +1670,22 @@ bool ScDocShell::LoadExternal( SfxMedium& rMed )
        const OUString& rFilterName = pFilter->GetName();
        if (rFilterName == "gnumeric")
        {
            if (!pOrcus->importGnumeric(m_aDocument, rMed))
            if (!pOrcus->importGnumeric(*m_pDocument, rMed))
                return false;
        }
        else if (rFilterName == "csv")
        {
            if (!pOrcus->importCSV(m_aDocument, rMed))
            if (!pOrcus->importCSV(*m_pDocument, rMed))
                return false;
        }
        else if (rFilterName == "xlsx")
        {
            if (!pOrcus->importXLSX(m_aDocument, rMed))
            if (!pOrcus->importXLSX(*m_pDocument, rMed))
                return false;
        }
        else if (rFilterName == "ods")
        {
            if (!pOrcus->importODS(m_aDocument, rMed))
            if (!pOrcus->importODS(*m_pDocument, rMed))
                return false;
        }

@@ -1701,19 +1701,19 @@ ScDocShell::PrepareSaveGuard::PrepareSaveGuard( ScDocShell& rDocShell )
{
    // DoEnterHandler not here (because of AutoSave), is in ExecuteSave.

    ScChartListenerCollection* pCharts = mrDocShell.m_aDocument.GetChartListenerCollection();
    ScChartListenerCollection* pCharts = mrDocShell.m_pDocument->GetChartListenerCollection();
    if (pCharts)
        pCharts->UpdateDirtyCharts();                           // Charts to be updated.
    mrDocShell.m_aDocument.StopTemporaryChartLock();
    mrDocShell.m_pDocument->StopTemporaryChartLock();
    if (mrDocShell.m_pAutoStyleList)
        mrDocShell.m_pAutoStyleList->ExecuteAllNow();             // Execute template timeouts now.
    if (mrDocShell.m_aDocument.HasExternalRefManager())
    if (mrDocShell.m_pDocument->HasExternalRefManager())
    {
        ScExternalRefManager* pRefMgr = mrDocShell.m_aDocument.GetExternalRefManager();
        ScExternalRefManager* pRefMgr = mrDocShell.m_pDocument->GetExternalRefManager();
        if (pRefMgr && pRefMgr->hasExternalData())
        {
            pRefMgr->setAllCacheTableReferencedStati( false);
            mrDocShell.m_aDocument.MarkUsedExternalReferences();  // Mark tables of external references to be written.
            mrDocShell.m_pDocument->MarkUsedExternalReferences();  // Mark tables of external references to be written.
        }
    }
    if (mrDocShell.GetCreateMode()== SfxObjectCreateMode::STANDARD)
@@ -1722,9 +1722,9 @@ ScDocShell::PrepareSaveGuard::PrepareSaveGuard( ScDocShell& rDocShell )

ScDocShell::PrepareSaveGuard::~PrepareSaveGuard() COVERITY_NOEXCEPT_FALSE
{
    if (mrDocShell.m_aDocument.HasExternalRefManager())
    if (mrDocShell.m_pDocument->HasExternalRefManager())
    {
        ScExternalRefManager* pRefMgr = mrDocShell.m_aDocument.GetExternalRefManager();
        ScExternalRefManager* pRefMgr = mrDocShell.m_pDocument->GetExternalRefManager();
        if (pRefMgr && pRefMgr->hasExternalData())
        {
            // Prevent accidental data loss due to lack of knowledge.
@@ -1735,7 +1735,7 @@ ScDocShell::PrepareSaveGuard::~PrepareSaveGuard() COVERITY_NOEXCEPT_FALSE

bool ScDocShell::Save()
{
    ScRefreshTimerProtector aProt( m_aDocument.GetRefreshTimerControlAddress() );
    ScRefreshTimerProtector aProt( m_pDocument->GetRefreshTimerControlAddress() );

    PrepareSaveGuard aPrepareGuard( *this);

@@ -1795,18 +1795,18 @@ bool ScDocShell::SaveAs( SfxMedium& rMedium )
        if (!aRel.isEmpty())
        {
            // Directory path will change before and after the save.
            m_aDocument.InvalidateStreamOnSave();
            m_pDocument->InvalidateStreamOnSave();
        }
    }

    ScTabViewShell* pViewShell = GetBestViewShell();
    bool bNeedsRehash = ScPassHashHelper::needsPassHashRegen(m_aDocument, PASSHASH_SHA1);
    bool bNeedsRehash = ScPassHashHelper::needsPassHashRegen(*m_pDocument, PASSHASH_SHA1);
    if (bNeedsRehash)
        // legacy xls hash double-hashed by SHA1 is also supported.
        bNeedsRehash = ScPassHashHelper::needsPassHashRegen(m_aDocument, PASSHASH_XL, PASSHASH_SHA1);
        bNeedsRehash = ScPassHashHelper::needsPassHashRegen(*m_pDocument, PASSHASH_XL, PASSHASH_SHA1);
    if (bNeedsRehash)
    {   // SHA256 explicitly supported in ODF 1.2, implicitly in ODF 1.1
        bNeedsRehash = ScPassHashHelper::needsPassHashRegen(m_aDocument, PASSHASH_SHA256);
        bNeedsRehash = ScPassHashHelper::needsPassHashRegen(*m_pDocument, PASSHASH_SHA256);
    }

    if (pViewShell && bNeedsRehash)
@@ -1816,7 +1816,7 @@ bool ScDocShell::SaveAs( SfxMedium& rMedium )
            return false;
    }

    ScRefreshTimerProtector aProt( m_aDocument.GetRefreshTimerControlAddress() );
    ScRefreshTimerProtector aProt( m_pDocument->GetRefreshTimerControlAddress() );

    PrepareSaveGuard aPrepareGuard( *this);

@@ -1968,13 +1968,13 @@ void ScDocShell::AsciiSave( SvStream& rStream, const ScImportOptions& rAsciiOpt,
    SCROW nStartRow = 0;
    SCCOL nEndCol;
    SCROW nEndRow;
    m_aDocument.GetCellArea( nTab, nEndCol, nEndRow );
    m_pDocument->GetCellArea( nTab, nEndCol, nEndRow );

    ScProgress aProgress( this, ScResId( STR_SAVE_DOC ), nEndRow, true );

    OUString aString;

    bool bTabProtect = m_aDocument.IsTabProtected( nTab );
    bool bTabProtect = m_pDocument->IsTabProtected( nTab );

    SCCOL nCol;
    SCROW nRow;
@@ -1984,7 +1984,7 @@ void ScDocShell::AsciiSave( SvStream& rStream, const ScImportOptions& rAsciiOpt,
    if (!bFixedWidth && cDelim != 0)
    {
        // First row iterator.
        ScHorizontalCellIterator aIter( m_aDocument, nTab, nStartCol, nStartRow, nEndCol, nStartRow);
        ScHorizontalCellIterator aIter( *m_pDocument, nTab, nStartCol, nStartRow, nEndCol, nStartRow);
        ScRefCellValue* pCell;
        // Must be first column and all following cells on this row must be
        // empty to fiddle with "sep=".
@@ -2025,9 +2025,9 @@ void ScDocShell::AsciiSave( SvStream& rStream, const ScImportOptions& rAsciiOpt,
    SCROW nNextRow = nStartRow;
    SCCOL nEmptyCol;
    SCROW nEmptyRow;
    SvNumberFormatter& rFormatter = *m_aDocument.GetFormatTable();
    SvNumberFormatter& rFormatter = *m_pDocument->GetFormatTable();

    ScHorizontalCellIterator aIter( m_aDocument, nTab, nStartCol, nStartRow,
    ScHorizontalCellIterator aIter( *m_pDocument, nTab, nStartCol, nStartRow,
        nEndCol, nEndRow );
    ScRefCellValue* pCell;
    while ( ( pCell = aIter.GetNext( nCol, nRow ) ) != nullptr )
@@ -2040,7 +2040,7 @@ void ScDocShell::AsciiSave( SvStream& rStream, const ScImportOptions& rAsciiOpt,
            {   // remaining columns of last row
                if ( bFixedWidth )
                    lcl_ScDocShell_WriteEmptyFixedWidthString( rStream,
                            m_aDocument, nTab, nEmptyCol );
                            *m_pDocument, nTab, nEmptyCol );
                else if ( cDelim != 0 )
                    rStream.WriteUniOrByteChar( cDelim );
            }
@@ -2052,7 +2052,7 @@ void ScDocShell::AsciiSave( SvStream& rStream, const ScImportOptions& rAsciiOpt,
                {
                    if ( bFixedWidth )
                        lcl_ScDocShell_WriteEmptyFixedWidthString( rStream,
                                m_aDocument, nTab, nEmptyCol );
                                *m_pDocument, nTab, nEmptyCol );
                    else if ( cDelim != 0 )
                        rStream.WriteUniOrByteChar( cDelim );
                }
@@ -2062,7 +2062,7 @@ void ScDocShell::AsciiSave( SvStream& rStream, const ScImportOptions& rAsciiOpt,
            {   // empty columns at beginning of row
                if ( bFixedWidth )
                    lcl_ScDocShell_WriteEmptyFixedWidthString( rStream,
                            m_aDocument, nTab, nEmptyCol );
                            *m_pDocument, nTab, nEmptyCol );
                else if ( cDelim != 0 )
                    rStream.WriteUniOrByteChar( cDelim );
            }
@@ -2074,7 +2074,7 @@ void ScDocShell::AsciiSave( SvStream& rStream, const ScImportOptions& rAsciiOpt,
            {   // columns in between
                if ( bFixedWidth )
                    lcl_ScDocShell_WriteEmptyFixedWidthString( rStream,
                            m_aDocument, nTab, nEmptyCol );
                            *m_pDocument, nTab, nEmptyCol );
                else if ( cDelim != 0 )
                    rStream.WriteUniOrByteChar( cDelim );
            }
@@ -2093,7 +2093,7 @@ void ScDocShell::AsciiSave( SvStream& rStream, const ScImportOptions& rAsciiOpt,
        if ( bTabProtect )
        {
            const ScProtectionAttr* pProtAttr =
                m_aDocument.GetAttr( nCol, nRow, nTab, ATTR_PROTECTION );
                m_pDocument->GetAttr( nCol, nRow, nTab, ATTR_PROTECTION );
            if ( pProtAttr->GetHideCell() ||
                    ( eType == CELLTYPE_FORMULA && bShowFormulas &&
                      pProtAttr->GetHideFormula() ) )
@@ -2122,16 +2122,16 @@ void ScDocShell::AsciiSave( SvStream& rStream, const ScImportOptions& rAsciiOpt,
                    }
                    else if (pCell->mpFormula->IsValue())
                    {
                        sal_uInt32 nFormat = m_aDocument.GetNumberFormat(aPos);
                        sal_uInt32 nFormat = m_pDocument->GetNumberFormat(aPos);
                        if ( bFixedWidth || bSaveAsShown )
                        {
                            const Color* pDummy;
                            aString = ScCellFormat::GetString(*pCell, nFormat, &pDummy, rFormatter, m_aDocument);
                            aString = ScCellFormat::GetString(*pCell, nFormat, &pDummy, rFormatter, *m_pDocument);
                            bString = bSaveAsShown && rFormatter.IsTextFormat( nFormat);
                        }
                        else
                        {
                            aString = ScCellFormat::GetInputString(*pCell, nFormat, rFormatter, m_aDocument);
                            aString = ScCellFormat::GetInputString(*pCell, nFormat, rFormatter, *m_pDocument);
                            bString = bForceQuotes = !bSaveNumberAsSuch;
                        }
                    }
@@ -2139,9 +2139,9 @@ void ScDocShell::AsciiSave( SvStream& rStream, const ScImportOptions& rAsciiOpt,
                    {
                        if ( bSaveAsShown )
                        {
                            sal_uInt32 nFormat = m_aDocument.GetNumberFormat(aPos);
                            sal_uInt32 nFormat = m_pDocument->GetNumberFormat(aPos);
                            const Color* pDummy;
                            aString = ScCellFormat::GetString(*pCell, nFormat, &pDummy, rFormatter, m_aDocument);
                            aString = ScCellFormat::GetString(*pCell, nFormat, &pDummy, rFormatter, *m_pDocument);
                        }
                        else
                            aString = pCell->mpFormula->GetString().getString();
@@ -2152,9 +2152,9 @@ void ScDocShell::AsciiSave( SvStream& rStream, const ScImportOptions& rAsciiOpt,
            case CELLTYPE_STRING :
                if ( bSaveAsShown )
                {
                    sal_uInt32 nFormat = m_aDocument.GetNumberFormat(aPos);
                    sal_uInt32 nFormat = m_pDocument->GetNumberFormat(aPos);
                    const Color* pDummy;
                    aString = ScCellFormat::GetString(*pCell, nFormat, &pDummy, rFormatter, m_aDocument);
                    aString = ScCellFormat::GetString(*pCell, nFormat, &pDummy, rFormatter, *m_pDocument);
                }
                else
                    aString = pCell->mpString->getString();
@@ -2163,7 +2163,7 @@ void ScDocShell::AsciiSave( SvStream& rStream, const ScImportOptions& rAsciiOpt,
            case CELLTYPE_EDIT :
                {
                    const EditTextObject* pObj = pCell->mpEditText;
                    EditEngine& rEngine = m_aDocument.GetEditEngine();
                    EditEngine& rEngine = m_pDocument->GetEditEngine();
                    rEngine.SetText( *pObj);
                    aString = rEngine.GetText();  // including LF
                    bString = true;
@@ -2171,16 +2171,16 @@ void ScDocShell::AsciiSave( SvStream& rStream, const ScImportOptions& rAsciiOpt,
                break;
            case CELLTYPE_VALUE :
                {
                    sal_uInt32 nFormat = m_aDocument.GetNumberFormat( nCol, nRow, nTab );
                    sal_uInt32 nFormat = m_pDocument->GetNumberFormat( nCol, nRow, nTab );
                    if ( bFixedWidth || bSaveAsShown )
                    {
                        const Color* pDummy;
                        aString = ScCellFormat::GetString(*pCell, nFormat, &pDummy, rFormatter, m_aDocument);
                        aString = ScCellFormat::GetString(*pCell, nFormat, &pDummy, rFormatter, *m_pDocument);
                        bString = bSaveAsShown && rFormatter.IsTextFormat( nFormat);
                    }
                    else
                    {
                        aString = ScCellFormat::GetInputString(*pCell, nFormat, rFormatter, m_aDocument);
                        aString = ScCellFormat::GetInputString(*pCell, nFormat, rFormatter, *m_pDocument);
                        bString = bForceQuotes = !bSaveNumberAsSuch;
                    }
                }
@@ -2194,8 +2194,8 @@ void ScDocShell::AsciiSave( SvStream& rStream, const ScImportOptions& rAsciiOpt,
        if ( bFixedWidth )
        {
            SvxCellHorJustify eHorJust =
                m_aDocument.GetAttr( nCol, nRow, nTab, ATTR_HOR_JUSTIFY )->GetValue();
            lcl_ScDocShell_GetFixedWidthString( aString, m_aDocument, nTab, nCol,
                m_pDocument->GetAttr( nCol, nRow, nTab, ATTR_HOR_JUSTIFY )->GetValue();
            lcl_ScDocShell_GetFixedWidthString( aString, *m_pDocument, nTab, nCol,
                    !bString, eHorJust );
            rStream.WriteUnicodeOrByteText( aString );
        }
@@ -2317,7 +2317,7 @@ void ScDocShell::AsciiSave( SvStream& rStream, const ScImportOptions& rAsciiOpt,
        {   // remaining empty columns of last row
            if ( bFixedWidth )
                lcl_ScDocShell_WriteEmptyFixedWidthString( rStream,
                        m_aDocument, nTab, nEmptyCol );
                        *m_pDocument, nTab, nEmptyCol );
            else if ( cDelim != 0 )
                rStream.WriteUniOrByteChar( cDelim );
        }
@@ -2330,7 +2330,7 @@ void ScDocShell::AsciiSave( SvStream& rStream, const ScImportOptions& rAsciiOpt,
        {
            if ( bFixedWidth )
                lcl_ScDocShell_WriteEmptyFixedWidthString( rStream,
                        m_aDocument, nTab, nEmptyCol );
                        *m_pDocument, nTab, nEmptyCol );
            else if ( cDelim != 0 )
                rStream.WriteUniOrByteChar( cDelim );
        }
@@ -2343,7 +2343,7 @@ void ScDocShell::AsciiSave( SvStream& rStream, const ScImportOptions& rAsciiOpt,

bool ScDocShell::ConvertTo( SfxMedium &rMed )
{
    ScRefreshTimerProtector aProt( m_aDocument.GetRefreshTimerControlAddress() );
    ScRefreshTimerProtector aProt( m_pDocument->GetRefreshTimerControlAddress() );

    //  #i6500# don't call DoEnterHandler here (doesn't work with AutoSave),
    //  it's already in ExecuteSave (as for Save and SaveAs)
@@ -2373,11 +2373,11 @@ bool ScDocShell::ConvertTo( SfxMedium &rMed )
        bool bDoSave = true;
        if( ScTabViewShell* pViewShell = GetBestViewShell() )
        {
            ScExtDocOptions* pExtDocOpt = m_aDocument.GetExtDocOptions();
            ScExtDocOptions* pExtDocOpt = m_pDocument->GetExtDocOptions();
            if( !pExtDocOpt )
            {
                m_aDocument.SetExtDocOptions( std::make_unique<ScExtDocOptions>() );
                pExtDocOpt = m_aDocument.GetExtDocOptions();
                m_pDocument->SetExtDocOptions( std::make_unique<ScExtDocOptions>() );
                pExtDocOpt = m_pDocument->GetExtDocOptions();
            }
            pViewShell->GetViewData().WriteExtOptions( *pExtDocOpt );

@@ -2398,7 +2398,7 @@ bool ScDocShell::ConvertTo( SfxMedium &rMed )

            if( bDoSave )
            {
                bool bNeedRetypePassDlg = ScPassHashHelper::needsPassHashRegen( m_aDocument, PASSHASH_XL );
                bool bNeedRetypePassDlg = ScPassHashHelper::needsPassHashRegen( *m_pDocument, PASSHASH_XL );
                bDoSave = !bNeedRetypePassDlg || pViewShell->ExecuteRetypePassDlg( PASSHASH_XL );
            }
        }
@@ -2408,7 +2408,7 @@ bool ScDocShell::ConvertTo( SfxMedium &rMed )
            ExportFormatExcel eFormat = ExpBiff5;
            if( aFltName == pFilterExcel97 || aFltName == pFilterEx97Temp )
                eFormat = ExpBiff8;
            ErrCode eError = ScFormatFilter::Get().ScExportExcel5( rMed, &m_aDocument, eFormat, RTL_TEXTENCODING_MS_1252 );
            ErrCode eError = ScFormatFilter::Get().ScExportExcel5( rMed, m_pDocument.get(), eFormat, RTL_TEXTENCODING_MS_1252 );

            if( eError && !GetError() )
                SetError(eError);
@@ -2464,7 +2464,7 @@ bool ScDocShell::ConvertTo( SfxMedium &rMed )
            }

            SCTAB nStartTab;
            SCTAB nCount = m_aDocument.GetTableCount();
            SCTAB nCount = m_pDocument->GetTableCount();
            if (aOptions.nSheetToExport == -1)
            {
                // All sheets.
@@ -2501,7 +2501,7 @@ bool ScDocShell::ConvertTo( SfxMedium &rMed )
            for (SCTAB i = nStartTab; i < nCount; ++i)
            {
                OUString sTabName;
                if (!m_aDocument.GetName(i, sTabName))
                if (!m_pDocument->GetName(i, sTabName))
                    sTabName = OUString::number(i);
                INetURLObject aSheetURLObject(aURLObject);
                OUString sFileName = sBaseName + "-" + sTabName;
@@ -2543,7 +2543,7 @@ bool ScDocShell::ConvertTo( SfxMedium &rMed )
                AsciiSave(*pStream, aOptions, GetSaveTab());
                bRet = true;

                if (m_aDocument.GetTableCount() > 1)
                if (m_pDocument->GetTableCount() > 1)
                    if (!rMed.GetError())
                        rMed.SetError(SCWARN_EXPORT_ASCII);
            }
@@ -2643,11 +2643,11 @@ bool ScDocShell::ConvertTo( SfxMedium &rMed )
            }

            weld::WaitObject aWait( GetActiveDialogParent() );
            ScFormatFilter::Get().ScExportDif( *pStream, &m_aDocument, ScAddress(0,0,0),
            ScFormatFilter::Get().ScExportDif( *pStream, m_pDocument.get(), ScAddress(0,0,0),
                ScGlobal::GetCharsetValue(sItStr) );
            bRet = true;

            if (m_aDocument.GetTableCount() > 1)
            if (m_pDocument->GetTableCount() > 1)
                if (!rMed.GetError())
                    rMed.SetError(SCWARN_EXPORT_ASCII);
        }
@@ -2661,10 +2661,10 @@ bool ScDocShell::ConvertTo( SfxMedium &rMed )

            SCCOL nEndCol;
            SCROW nEndRow;
            m_aDocument.GetCellArea( 0, nEndCol, nEndRow );
            m_pDocument->GetCellArea( 0, nEndCol, nEndRow );
            ScRange aRange( 0,0,0, nEndCol,nEndRow,0 );

            ScImportExport aImExport( m_aDocument, aRange );
            ScImportExport aImExport( *m_pDocument, aRange );
            aImExport.SetFormulas( true );
            bRet = aImExport.ExportStream( *pStream, rMed.GetBaseURL( true ), SotClipboardFormatId::SYLK );
        }
@@ -2681,7 +2681,7 @@ bool ScDocShell::ConvertTo( SfxMedium &rMed )
                sFilterOptions = pOptionsItem->GetValue();

            weld::WaitObject aWait(GetActiveDialogParent());
            ScImportExport aImExport(m_aDocument);
            ScImportExport aImExport(*m_pDocument);
            aImExport.SetStreamPath(rMed.GetName());
            aImExport.SetFilterOptions(sFilterOptions);
            bRet = aImExport.ExportStream(*pStream, rMed.GetBaseURL(true), SotClipboardFormatId::HTML);
@@ -2735,7 +2735,7 @@ bool ScDocShell::QuerySlotExecutable( sal_uInt16 nSlotId )
    bool bSlotExecutable = true;
    if( nVbaEventId != VBAEventId::NO_EVENT ) try
    {
        uno::Reference< XVBAEventProcessor > xEventProcessor( m_aDocument.GetVbaEventProcessor(), uno::UNO_SET_THROW );
        uno::Reference< XVBAEventProcessor > xEventProcessor( m_pDocument->GetVbaEventProcessor(), uno::UNO_SET_THROW );
        xEventProcessor->processVbaEvent( nVbaEventId, aArgs );
    }
    catch( util::VetoException& )
@@ -2766,7 +2766,7 @@ bool ScDocShell::PrepareClose( bool bUI )

        return false;
    }
    if ( m_aDocument.IsInLinkUpdate() || m_aDocument.IsInInterpreter() )
    if ( m_pDocument->IsInLinkUpdate() || m_pDocument->IsInInterpreter() )
    {
        ErrorMessage(STR_CLOSE_ERROR_LINK);
        return false;
@@ -2779,7 +2779,7 @@ bool ScDocShell::PrepareClose( bool bUI )
    {
        try
        {
            uno::Reference< script::vba::XVBAEventProcessor > xVbaEvents( m_aDocument.GetVbaEventProcessor(), uno::UNO_SET_THROW );
            uno::Reference< script::vba::XVBAEventProcessor > xVbaEvents( m_pDocument->GetVbaEventProcessor(), uno::UNO_SET_THROW );
            uno::Sequence< uno::Any > aArgs;
            xVbaEvents->processVbaEvent( script::vba::VBAEventId::WORKBOOK_BEFORECLOSE, aArgs );
        }
@@ -2796,7 +2796,7 @@ bool ScDocShell::PrepareClose( bool bUI )

    bool bRet = SfxObjectShell::PrepareClose( bUI );
    if (bRet) // true == close
        m_aDocument.EnableIdle(false); // Do not mess around with it anymore!
        m_pDocument->EnableIdle(false); // Do not mess around with it anymore!

    return bRet;
}
@@ -2859,7 +2859,7 @@ std::unique_ptr<ScDocFunc> ScDocShell::CreateDocFunc()

ScDocShell::ScDocShell( const SfxModelFlags i_nSfxCreationFlags ) :
    SfxObjectShell( i_nSfxCreationFlags ),
    m_aDocument       ( SCDOCMODE_DOCUMENT, this ),
    m_pDocument       (std::make_shared<ScDocument>( SCDOCMODE_DOCUMENT, this )),
    m_aDdeTextFmt(OUString("TEXT")),
    m_nPrtToScreenFactor( 1.0 ),
    m_pImpl           ( new DocShell_Impl ),
@@ -2885,11 +2885,11 @@ ScDocShell::ScDocShell( const SfxModelFlags i_nSfxCreationFlags ) :
    ScModelObj::CreateAndSet( this );

    StartListening(*this);
    SfxStyleSheetPool* pStlPool = m_aDocument.GetStyleSheetPool();
    SfxStyleSheetPool* pStlPool = m_pDocument->GetStyleSheetPool();
    if (pStlPool)
        StartListening(*pStlPool);

    m_aDocument.GetDBCollection()->SetRefreshHandler(
    m_pDocument->GetDBCollection()->SetRefreshHandler(
        LINK( this, ScDocShell, RefreshDBDataHdl ) );

    // InitItems and CalcOutputFactor are called now in Load/ConvertFrom/InitNew
@@ -2899,7 +2899,7 @@ ScDocShell::~ScDocShell()
{
    ResetDrawObjectShell(); // If the Drawing Layer still tries to access it, access it

    SfxStyleSheetPool* pStlPool = m_aDocument.GetStyleSheetPool();
    SfxStyleSheetPool* pStlPool = m_pDocument->GetStyleSheetPool();
    if (pStlPool)
        EndListening(*pStlPool);
    EndListening(*this);
@@ -2911,8 +2911,8 @@ ScDocShell::~ScDocShell()
        pSfxApp->RemoveDdeTopic( this );

    m_pDocFunc.reset();
    delete m_aDocument.mpUndoManager;
    m_aDocument.mpUndoManager = nullptr;
    delete m_pDocument->mpUndoManager;
    m_pDocument->mpUndoManager = nullptr;
    m_pImpl.reset();

    m_pPaintLockData.reset();
@@ -2931,7 +2931,7 @@ ScDocShell::~ScDocShell()

SfxUndoManager* ScDocShell::GetUndoManager()
{
    return m_aDocument.GetUndoManager();
    return m_pDocument->GetUndoManager();
}

void ScDocShell::SetModified( bool bModified )
@@ -2953,9 +2953,9 @@ void ScDocShell::SetDocumentModified()
    {
        // #i115009# broadcast BCA_BRDCST_ALWAYS, so a component can read recalculated results
        // of RecalcModeAlways formulas (like OFFSET) after modifying cells
        m_aDocument.Broadcast(ScHint(SfxHintId::ScDataChanged, BCA_BRDCST_ALWAYS));
        m_aDocument.InvalidateTableArea();    // #i105279# needed here
        m_aDocument.BroadcastUno( SfxHint( SfxHintId::DataChanged ) );
        m_pDocument->Broadcast(ScHint(SfxHintId::ScDataChanged, BCA_BRDCST_ALWAYS));
        m_pDocument->InvalidateTableArea();    // #i105279# needed here
        m_pDocument->BroadcastUno( SfxHint( SfxHintId::DataChanged ) );

        m_pPaintLockData->SetModified(); // Later on ...
        return;
@@ -2963,18 +2963,18 @@ void ScDocShell::SetDocumentModified()

    SetDrawModified();

    if ( m_aDocument.IsAutoCalcShellDisabled() )
    if ( m_pDocument->IsAutoCalcShellDisabled() )
        SetDocumentModifiedPending( true );
    else
    {
        SetDocumentModifiedPending( false );
        m_aDocument.InvalidateStyleSheetUsage();
        m_aDocument.InvalidateTableArea();
        m_aDocument.InvalidateLastTableOpParams();
        m_aDocument.Broadcast(ScHint(SfxHintId::ScDataChanged, BCA_BRDCST_ALWAYS));
        if ( m_aDocument.IsForcedFormulaPending() && m_aDocument.GetAutoCalc() )
            m_aDocument.CalcFormulaTree( true );
        m_aDocument.RefreshDirtyTableColumnNames();
        m_pDocument->InvalidateStyleSheetUsage();
        m_pDocument->InvalidateTableArea();
        m_pDocument->InvalidateLastTableOpParams();
        m_pDocument->Broadcast(ScHint(SfxHintId::ScDataChanged, BCA_BRDCST_ALWAYS));
        if ( m_pDocument->IsForcedFormulaPending() && m_pDocument->GetAutoCalc() )
            m_pDocument->CalcFormulaTree( true );
        m_pDocument->RefreshDirtyTableColumnNames();
        PostDataChanged();

        //  Detective AutoUpdate:
@@ -2982,13 +2982,13 @@ void ScDocShell::SetDocumentModified()
        //  "Trace Error" entries (Trace Error can look completely different
        //  after changes to non-formula cells).

        ScDetOpList* pList = m_aDocument.GetDetOpList();
        if ( pList && ( m_aDocument.IsDetectiveDirty() || pList->HasAddError() ) &&
        ScDetOpList* pList = m_pDocument->GetDetOpList();
        if ( pList && ( m_pDocument->IsDetectiveDirty() || pList->HasAddError() ) &&
             pList->Count() && !IsInUndo() && SC_MOD()->GetAppOptions().GetDetectiveAuto() )
        {
            GetDocFunc().DetectiveRefresh(true);    // sal_True = caused by automatic update
        }
        m_aDocument.SetDetectiveDirty(false);         // always reset, also if not refreshed
        m_pDocument->SetDetectiveDirty(false);         // always reset, also if not refreshed
    }

    if (m_bAreasChangedNeedBroadcast)
@@ -2998,7 +2998,7 @@ void ScDocShell::SetDocumentModified()
    }

    // notify UNO objects after BCA_BRDCST_ALWAYS etc.
    m_aDocument.BroadcastUno( SfxHint( SfxHintId::DataChanged ) );
    m_pDocument->BroadcastUno( SfxHint( SfxHintId::DataChanged ) );
}

/**
@@ -3030,9 +3030,9 @@ void ScDocShell::SetDrawModified()
        pBindings->Invalidate( SID_REPEAT );
    }

    if ( m_aDocument.IsChartListenerCollectionNeedsUpdate() )
    if ( m_pDocument->IsChartListenerCollectionNeedsUpdate() )
    {
        m_aDocument.UpdateChartListenerCollection();
        m_pDocument->UpdateChartListenerCollection();
        SfxGetpApp()->Broadcast(SfxHint( SfxHintId::ScDrawChanged ));    // Navigator
    }
    SC_MOD()->AnythingChanged();
@@ -3047,7 +3047,7 @@ void ScDocShell::GetDocStat( ScDocStat& rDocStat )
{
    SfxPrinter* pPrinter = GetPrinter();

    m_aDocument.GetDocStat( rDocStat );
    m_pDocument->GetDocStat( rDocStat );
    rDocStat.nPageCount = 0;

    if ( pPrinter )
@@ -3243,7 +3243,7 @@ void ScDocShell::UseSheetSaveEntries()
    m_pSheetSaveData->UseSaveEntries();   // use positions from saved file for next saving

    bool bHasEntries = false;
    SCTAB nTabCount = m_aDocument.GetTableCount();
    SCTAB nTabCount = m_pDocument->GetTableCount();
    SCTAB nTab;
    for (nTab = 0; nTab < nTabCount; ++nTab)
        if (m_pSheetSaveData->HasStreamPos(nTab))
@@ -3254,7 +3254,7 @@ void ScDocShell::UseSheetSaveEntries()
        // if no positions were set (for example, export to other format),
        // reset all "valid" flags
        for (nTab = 0; nTab < nTabCount; ++nTab)
            m_aDocument.SetStreamValid(nTab, false);
            m_pDocument->SetStreamValid(nTab, false);
    }
}

@@ -3303,14 +3303,14 @@ void ScDocShellModificator::SetDocumentModified()

bool ScDocShell::IsChangeRecording() const
{
    ScChangeTrack* pChangeTrack = m_aDocument.GetChangeTrack();
    ScChangeTrack* pChangeTrack = m_pDocument->GetChangeTrack();
    return pChangeTrack != nullptr;
}

bool ScDocShell::HasChangeRecordProtection() const
{
    bool bRes = false;
    ScChangeTrack* pChangeTrack = m_aDocument.GetChangeTrack();
    ScChangeTrack* pChangeTrack = m_pDocument->GetChangeTrack();
    if (pChangeTrack)
        bRes = pChangeTrack->IsProtected();
    return bRes;
@@ -3322,14 +3322,14 @@ void ScDocShell::SetChangeRecording( bool bActivate, bool /*bLockAllViews*/ )

    if (bActivate)
    {
        m_aDocument.StartChangeTracking();
        m_pDocument->StartChangeTracking();
        ScChangeViewSettings aChangeViewSet;
        aChangeViewSet.SetShowChanges(true);
        m_aDocument.SetChangeViewSettings(aChangeViewSet);
        m_pDocument->SetChangeViewSettings(aChangeViewSet);
    }
    else
    {
        m_aDocument.EndChangeTracking();
        m_pDocument->EndChangeTracking();
        PostPaintGridAll();
    }

@@ -3345,7 +3345,7 @@ void ScDocShell::SetChangeRecording( bool bActivate, bool /*bLockAllViews*/ )

void ScDocShell::SetProtectionPassword( const OUString &rNewPassword )
{
    ScChangeTrack* pChangeTrack = m_aDocument.GetChangeTrack();
    ScChangeTrack* pChangeTrack = m_pDocument->GetChangeTrack();
    if (!pChangeTrack)
        return;

@@ -3375,7 +3375,7 @@ void ScDocShell::SetProtectionPassword( const OUString &rNewPassword )
bool ScDocShell::GetProtectionHash( /*out*/ css::uno::Sequence< sal_Int8 > &rPasswordHash )
{
    bool bRes = false;
    ScChangeTrack* pChangeTrack = m_aDocument.GetChangeTrack();
    ScChangeTrack* pChangeTrack = m_pDocument->GetChangeTrack();
    if (pChangeTrack && pChangeTrack->IsProtected())
    {
        rPasswordHash = pChangeTrack->GetProtection();
diff --git a/sc/source/ui/docshell/docsh2.cxx b/sc/source/ui/docshell/docsh2.cxx
index e02b815d..1668297 100644
--- a/sc/source/ui/docshell/docsh2.cxx
+++ b/sc/source/ui/docshell/docsh2.cxx
@@ -42,7 +42,7 @@ bool ScDocShell::InitNew( const uno::Reference < embed::XStorage >& xStor )
{
    bool bRet = SfxObjectShell::InitNew( xStor );

    m_aDocument.MakeTable(0);
    m_pDocument->MakeTable(0);

    //  Additional tables are created by the first View, if bIsEmpty is still sal_True
    if( bRet )
@@ -58,8 +58,8 @@ bool ScDocShell::InitNew( const uno::Reference < embed::XStorage >& xStor )
    // InitOptions sets the document languages, must be called before CreateStandardStyles
    InitOptions(false);

    m_aDocument.GetStyleSheetPool()->CreateStandardStyles();
    m_aDocument.UpdStlShtPtrsFrmNms();
    m_pDocument->GetStyleSheetPool()->CreateStandardStyles();
    m_pDocument->UpdStlShtPtrsFrmNms();

    if (!m_bUcalcTest)
    {
@@ -74,8 +74,8 @@ bool ScDocShell::InitNew( const uno::Reference < embed::XStorage >& xStor )
        ScOrcusFilters* pOrcus = ScFormatFilter::Get().GetOrcusFilters();
        if (pOrcus)
        {
            pOrcus->importODS_Styles(m_aDocument, aPath);
            m_aDocument.GetStyleSheetPool()->setAllParaStandard();
            pOrcus->importODS_Styles(*m_pDocument, aPath);
            m_pDocument->GetStyleSheetPool()->setAllParaStandard();
        }
    }

@@ -97,7 +97,7 @@ void ScDocShell::InitItems()
    // Printer Options are set in GetPrinter when printing
    UpdateFontList();

    ScDrawLayer* pDrawLayer = m_aDocument.GetDrawLayer();
    ScDrawLayer* pDrawLayer = m_pDocument->GetDrawLayer();
    if (pDrawLayer)
    {
        PutItem( SvxColorListItem  ( pDrawLayer->GetColorList(), SID_COLOR_TABLE ) );
@@ -118,13 +118,13 @@ void ScDocShell::InitItems()
    }

    if (utl::ConfigManager::IsFuzzing() ||
        (m_aDocument.GetForbiddenCharacters() && m_aDocument.IsValidAsianCompression() && m_aDocument.IsValidAsianKerning()))
        (m_pDocument->GetForbiddenCharacters() && m_pDocument->IsValidAsianCompression() && m_pDocument->IsValidAsianKerning()))
        return;

    //  get settings from SvxAsianConfig
    SvxAsianConfig aAsian;

    if (!m_aDocument.GetForbiddenCharacters())
    if (!m_pDocument->GetForbiddenCharacters())
    {
        // set forbidden characters if necessary
        const uno::Sequence<lang::Locale> aLocales = aAsian.GetStartEndCharLocales();
@@ -142,37 +142,37 @@ void ScDocShell::InitItems()
                xForbiddenTable->SetForbiddenCharacters( eLang, aForbidden );
            }

            m_aDocument.SetForbiddenCharacters( xForbiddenTable );
            m_pDocument->SetForbiddenCharacters( xForbiddenTable );
        }
    }

    if ( !m_aDocument.IsValidAsianCompression() )
    if ( !m_pDocument->IsValidAsianCompression() )
    {
        // set compression mode from configuration if not already set (e.g. XML import)
        m_aDocument.SetAsianCompression( aAsian.GetCharDistanceCompression() );
        m_pDocument->SetAsianCompression( aAsian.GetCharDistanceCompression() );
    }

    if ( !m_aDocument.IsValidAsianKerning() )
    if ( !m_pDocument->IsValidAsianKerning() )
    {
        // set asian punctuation kerning from configuration if not already set (e.g. XML import)
        m_aDocument.SetAsianKerning( !aAsian.IsKerningWesternTextOnly() );    // reversed
        m_pDocument->SetAsianKerning( !aAsian.IsKerningWesternTextOnly() );    // reversed
    }
}

void ScDocShell::ResetDrawObjectShell()
{
    ScDrawLayer* pDrawLayer = m_aDocument.GetDrawLayer();
    ScDrawLayer* pDrawLayer = m_pDocument->GetDrawLayer();
    if (pDrawLayer)
        pDrawLayer->SetObjectShell( nullptr );
}

ScDrawLayer* ScDocShell::MakeDrawLayer()
{
    ScDrawLayer* pDrawLayer = m_aDocument.GetDrawLayer();
    ScDrawLayer* pDrawLayer = m_pDocument->GetDrawLayer();
    if (!pDrawLayer)
    {
        m_aDocument.InitDrawLayer(this);
        pDrawLayer = m_aDocument.GetDrawLayer();
        m_pDocument->InitDrawLayer(this);
        pDrawLayer = m_pDocument->GetDrawLayer();
        InitItems(); // including Undo and Basic
        Broadcast( SfxHint( SfxHintId::ScDrawLayerNew ) );
        if (m_nDocumentLock)
diff --git a/sc/source/ui/docshell/docsh3.cxx b/sc/source/ui/docshell/docsh3.cxx
index 956b837..edab7a5 100644
--- a/sc/source/ui/docshell/docsh3.cxx
+++ b/sc/source/ui/docshell/docsh3.cxx
@@ -94,7 +94,7 @@ void ScDocShell::PostDataChanged()
{
    Broadcast( SfxHint( SfxHintId::ScDataChanged ) );
    SfxGetpApp()->Broadcast(SfxHint( SfxHintId::ScAnyDataChanged ));      // Navigator
    m_aDocument.PrepareFormulaCalc();
    m_pDocument->PrepareFormulaCalc();
    //! notify navigator directly!
}

@@ -116,10 +116,10 @@ void ScDocShell::PostPaint( const ScRangeList& rRanges, PaintPartFlags nPart, sa
        SCROW nRow1 = rRange.aStart.Row(), nRow2 = rRange.aEnd.Row();
        SCTAB nTab1 = rRange.aStart.Tab(), nTab2 = rRange.aEnd.Tab();

        if (!m_aDocument.ValidCol(nCol1)) nCol1 = m_aDocument.MaxCol();
        if (!m_aDocument.ValidRow(nRow1)) nRow1 = m_aDocument.MaxRow();
        if (!m_aDocument.ValidCol(nCol2)) nCol2 = m_aDocument.MaxCol();
        if (!m_aDocument.ValidRow(nRow2)) nRow2 = m_aDocument.MaxRow();
        if (!m_pDocument->ValidCol(nCol1)) nCol1 = m_pDocument->MaxCol();
        if (!m_pDocument->ValidRow(nRow1)) nRow1 = m_pDocument->MaxRow();
        if (!m_pDocument->ValidCol(nCol2)) nCol2 = m_pDocument->MaxCol();
        if (!m_pDocument->ValidRow(nRow2)) nRow2 = m_pDocument->MaxRow();

        if ( m_pPaintLockData )
        {
@@ -142,16 +142,16 @@ void ScDocShell::PostPaint( const ScRangeList& rRanges, PaintPartFlags nPart, sa
        {
                                                //! check for hidden columns/rows!
            if (nCol1>0) --nCol1;
            if (nCol2<m_aDocument.MaxCol()) ++nCol2;
            if (nCol2<m_pDocument->MaxCol()) ++nCol2;
            if (nRow1>0) --nRow1;
            if (nRow2<m_aDocument.MaxRow()) ++nRow2;
            if (nRow2<m_pDocument->MaxRow()) ++nRow2;
        }

                                                // expand for the merged ones
        if (nExtFlags & SC_PF_TESTMERGE)
            m_aDocument.ExtendMerge( nCol1, nRow1, nCol2, nRow2, nTab1 );
            m_pDocument->ExtendMerge( nCol1, nRow1, nCol2, nRow2, nTab1 );

        if ( nCol1 != 0 || nCol2 != m_aDocument.MaxCol() )
        if ( nCol1 != 0 || nCol2 != m_pDocument->MaxCol() )
        {
            //  Extend to whole rows if SC_PF_WHOLEROWS is set, or rotated or non-left
            //  aligned cells are contained (see UpdatePaintExt).
@@ -159,11 +159,11 @@ void ScDocShell::PostPaint( const ScRangeList& rRanges, PaintPartFlags nPart, sa
            //  support of right-aligned text.

            if ( ( nExtFlags & SC_PF_WHOLEROWS ) ||
                 m_aDocument.HasAttrib( nCol1,nRow1,nTab1,
                                      m_aDocument.MaxCol(),nRow2,nTab2, HasAttrFlags::Rotate | HasAttrFlags::RightOrCenter ) )
                 m_pDocument->HasAttrib( nCol1,nRow1,nTab1,
                                      m_pDocument->MaxCol(),nRow2,nTab2, HasAttrFlags::Rotate | HasAttrFlags::RightOrCenter ) )
            {
                nCol1 = 0;
                nCol2 = m_aDocument.MaxCol();
                nCol2 = m_pDocument->MaxCol();
            }
        }
        aPaintRanges.push_back(ScRange(nCol1, nRow1, nTab1, nCol2, nRow2, nTab2));
@@ -182,7 +182,7 @@ void ScDocShell::PostPaint( const ScRangeList& rRanges, PaintPartFlags nPart, sa

void ScDocShell::PostPaintGridAll()
{
    PostPaint( 0,0,0, m_aDocument.MaxCol(),m_aDocument.MaxRow(),MAXTAB, PaintPartFlags::Grid );
    PostPaint( 0,0,0, m_pDocument->MaxCol(),m_pDocument->MaxRow(),MAXTAB, PaintPartFlags::Grid );
}

void ScDocShell::PostPaintCell( SCCOL nCol, SCROW nRow, SCTAB nTab )
@@ -197,13 +197,13 @@ void ScDocShell::PostPaintCell( const ScAddress& rPos )

void ScDocShell::PostPaintExtras()
{
    PostPaint( 0,0,0, m_aDocument.MaxCol(),m_aDocument.MaxRow(),MAXTAB, PaintPartFlags::Extras );
    PostPaint( 0,0,0, m_pDocument->MaxCol(),m_pDocument->MaxRow(),MAXTAB, PaintPartFlags::Extras );
}

void ScDocShell::UpdatePaintExt( sal_uInt16& rExtFlags, const ScRange& rRange )
{
    if ( ( rExtFlags & SC_PF_LINES ) == 0 &&
         m_aDocument.HasAttrib( rRange, HasAttrFlags::Lines | HasAttrFlags::Shadow | HasAttrFlags::Conditional ) )
         m_pDocument->HasAttrib( rRange, HasAttrFlags::Lines | HasAttrFlags::Shadow | HasAttrFlags::Conditional ) )
    {
        //  If the range contains lines, shadow or conditional formats,
        //  set SC_PF_LINES to include one extra cell in all directions.
@@ -212,8 +212,8 @@ void ScDocShell::UpdatePaintExt( sal_uInt16& rExtFlags, const ScRange& rRange )
    }

    if ( ( rExtFlags & SC_PF_WHOLEROWS ) == 0 &&
         ( rRange.aStart.Col() != 0 || rRange.aEnd.Col() != m_aDocument.MaxCol() ) &&
         m_aDocument.HasAttrib( rRange, HasAttrFlags::Rotate | HasAttrFlags::RightOrCenter ) )
         ( rRange.aStart.Col() != 0 || rRange.aEnd.Col() != m_pDocument->MaxCol() ) &&
         m_pDocument->HasAttrib( rRange, HasAttrFlags::Rotate | HasAttrFlags::RightOrCenter ) )
    {
        //  If the range contains (logically) right- or center-aligned cells,
        //  or rotated cells, set SC_PF_WHOLEROWS to paint the whole rows.
@@ -279,7 +279,7 @@ void ScDocShell::LockDocument_Impl(sal_uInt16 nNew)
{
    if (!m_nDocumentLock)
    {
        ScDrawLayer* pDrawLayer = m_aDocument.GetDrawLayer();
        ScDrawLayer* pDrawLayer = m_pDocument->GetDrawLayer();
        if (pDrawLayer)
            pDrawLayer->setLock(true);
    }
@@ -291,7 +291,7 @@ void ScDocShell::UnlockDocument_Impl(sal_uInt16 nNew)
    m_nDocumentLock = nNew;
    if (!m_nDocumentLock)
    {
        ScDrawLayer* pDrawLayer = m_aDocument.GetDrawLayer();
        ScDrawLayer* pDrawLayer = m_pDocument->GetDrawLayer();
        if (pDrawLayer)
            pDrawLayer->setLock(false);
    }
@@ -370,7 +370,7 @@ void ScDocShell::CalcOutputFactor()
    OUString aTestString(
            "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01234567890123456789");
    tools::Long nPrinterWidth = 0;
    const ScPatternAttr* pPattern = &m_aDocument.GetPool()->GetDefaultItem(ATTR_PATTERN);
    const ScPatternAttr* pPattern = &m_pDocument->GetPool()->GetDefaultItem(ATTR_PATTERN);

    vcl::Font aDefFont;
    OutputDevice* pRefDev = GetRefDevice();
@@ -434,23 +434,23 @@ void ScDocShell::InitOptions(bool bForLoading)      // called from InitNew and L
        aDocOpt.SetDate( 30, 12, 1899);
    }

    m_aDocument.SetDocOptions( aDocOpt );
    m_aDocument.SetViewOptions( aViewOpt );
    m_pDocument->SetDocOptions( aDocOpt );
    m_pDocument->SetViewOptions( aViewOpt );
    SetFormulaOptions( aFormulaOpt, bForLoading );

    //  print options are now set directly before the printing

    m_aDocument.SetLanguage( nDefLang, nCjkLang, nCtlLang );
    m_pDocument->SetLanguage( nDefLang, nCjkLang, nCtlLang );
}

Printer* ScDocShell::GetDocumentPrinter()       // for OLE
{
    return m_aDocument.GetPrinter();
    return m_pDocument->GetPrinter();
}

SfxPrinter* ScDocShell::GetPrinter(bool bCreateIfNotExist)
{
    return m_aDocument.GetPrinter(bCreateIfNotExist);
    return m_pDocument->GetPrinter(bCreateIfNotExist);
}

void ScDocShell::UpdateFontList()
@@ -465,21 +465,21 @@ void ScDocShell::UpdateFontList()

OutputDevice* ScDocShell::GetRefDevice()
{
    return m_aDocument.GetRefDevice();
    return m_pDocument->GetRefDevice();
}

sal_uInt16 ScDocShell::SetPrinter( VclPtr<SfxPrinter> const & pNewPrinter, SfxPrinterChangeFlags nDiffFlags )
{
    SfxPrinter *pOld = m_aDocument.GetPrinter( false );
    SfxPrinter *pOld = m_pDocument->GetPrinter( false );
    if ( pOld && pOld->IsPrinting() )
        return SFX_PRINTERROR_BUSY;

    if (nDiffFlags & SfxPrinterChangeFlags::PRINTER)
    {
        if ( m_aDocument.GetPrinter() != pNewPrinter )
        if ( m_pDocument->GetPrinter() != pNewPrinter )
        {
            m_aDocument.SetPrinter( pNewPrinter );
            m_aDocument.SetPrintOptions();
            m_pDocument->SetPrinter( pNewPrinter );
            m_pDocument->SetPrintOptions();

            // MT: Use UpdateFontList: Will use Printer fonts only if needed!
            /*
@@ -510,7 +510,7 @@ sal_uInt16 ScDocShell::SetPrinter( VclPtr<SfxPrinter> const & pNewPrinter, SfxPr
    }
    else if (nDiffFlags & SfxPrinterChangeFlags::JOBSETUP)
    {
        SfxPrinter* pOldPrinter = m_aDocument.GetPrinter();
        SfxPrinter* pOldPrinter = m_pDocument->GetPrinter();
        if (pOldPrinter)
        {
            pOldPrinter->SetJobSetup( pNewPrinter->GetJobSetup() );
@@ -518,20 +518,20 @@ sal_uInt16 ScDocShell::SetPrinter( VclPtr<SfxPrinter> const & pNewPrinter, SfxPr
            //  #i6706# Call SetPrinter with the old printer again, so the drawing layer
            //  RefDevice is set (calling ReformatAllTextObjects and rebuilding charts),
            //  because the JobSetup (printer device settings) may affect text layout.
            m_aDocument.SetPrinter( pOldPrinter );
            m_pDocument->SetPrinter( pOldPrinter );
            CalcOutputFactor();                         // also with the new settings
        }
    }

    if (nDiffFlags & SfxPrinterChangeFlags::OPTIONS)
    {
        m_aDocument.SetPrintOptions();        //! from new printer ???
        m_pDocument->SetPrintOptions();        //! from new printer ???
    }

    if (nDiffFlags & (SfxPrinterChangeFlags::CHG_ORIENTATION | SfxPrinterChangeFlags::CHG_SIZE))
    {
        OUString aStyle = m_aDocument.GetPageStyle( GetCurTab() );
        ScStyleSheetPool* pStPl = m_aDocument.GetStyleSheetPool();
        OUString aStyle = m_pDocument->GetPageStyle( GetCurTab() );
        ScStyleSheetPool* pStPl = m_pDocument->GetStyleSheetPool();
        SfxStyleSheet* pStyleSheet = static_cast<SfxStyleSheet*>(pStPl->Find(aStyle, SfxStyleFamily::Page));
        if (pStyleSheet)
        {
@@ -564,7 +564,7 @@ sal_uInt16 ScDocShell::SetPrinter( VclPtr<SfxPrinter> const & pNewPrinter, SfxPr
        }
    }

    PostPaint(0,0,0,m_aDocument.MaxCol(),m_aDocument.MaxRow(),MAXTAB,PaintPartFlags::All);
    PostPaint(0,0,0,m_pDocument->MaxCol(),m_pDocument->MaxRow(),MAXTAB,PaintPartFlags::All);

    return 0;
}
@@ -659,17 +659,17 @@ void ScDocShell::ExecuteChangeCommentDialog( ScChangeAction* pAction, weld::Wind

void ScDocShell::CompareDocument( ScDocument& rOtherDoc )
{
    ScChangeTrack* pTrack = m_aDocument.GetChangeTrack();
    ScChangeTrack* pTrack = m_pDocument->GetChangeTrack();
    if ( pTrack && pTrack->GetFirst() )
    {
        //! there are changes -> inquiry if needs to be deleted
    }

    m_aDocument.EndChangeTracking();
    m_aDocument.StartChangeTracking();
    m_pDocument->EndChangeTracking();
    m_pDocument->StartChangeTracking();

    OUString aOldUser;
    pTrack = m_aDocument.GetChangeTrack();
    pTrack = m_pDocument->GetChangeTrack();
    if ( pTrack )
    {
        aOldUser = pTrack->GetUser();
@@ -708,9 +708,9 @@ void ScDocShell::CompareDocument( ScDocument& rOtherDoc )
        }
    }

    m_aDocument.CompareDocument( rOtherDoc );
    m_pDocument->CompareDocument( rOtherDoc );

    pTrack = m_aDocument.GetChangeTrack();
    pTrack = m_pDocument->GetChangeTrack();
    if ( pTrack )
        pTrack->SetUser( aOldUser );

@@ -774,18 +774,18 @@ void ScDocShell::MergeDocument( ScDocument& rOtherDoc, bool bShared, bool bCheck
    if (!pSourceTrack)
        return;             //! nothing to do - error notification?

    ScChangeTrack* pThisTrack = m_aDocument.GetChangeTrack();
    ScChangeTrack* pThisTrack = m_pDocument->GetChangeTrack();
    if ( !pThisTrack )
    {   // turn on
        m_aDocument.StartChangeTracking();
        pThisTrack = m_aDocument.GetChangeTrack();
        m_pDocument->StartChangeTracking();
        pThisTrack = m_pDocument->GetChangeTrack();
        OSL_ENSURE(pThisTrack,"ChangeTracking not enabled?");
        if ( !bShared )
        {
            // turn on visual RedLining
            ScChangeViewSettings aChangeViewSet;
            aChangeViewSet.SetShowChanges(true);
            m_aDocument.SetChangeViewSettings(aChangeViewSet);
            m_pDocument->SetChangeViewSettings(aChangeViewSet);
        }
    }

@@ -892,7 +892,7 @@ void ScDocShell::MergeDocument( ScDocument& rOtherDoc, bool bShared, bool bCheck
        bool bMergeAction = false;
        if ( bShared )
        {
            if ( !bCheckDuplicates || !lcl_FindAction( rOtherDoc, pSourceAction, m_aDocument, pFirstSearchAction, pLastSearchAction, bIgnore100Sec ) )
            if ( !bCheckDuplicates || !lcl_FindAction( rOtherDoc, pSourceAction, *m_pDocument, pFirstSearchAction, pLastSearchAction, bIgnore100Sec ) )
            {
                bMergeAction = true;
            }
@@ -920,7 +920,7 @@ void ScDocShell::MergeDocument( ScDocument& rOtherDoc, bool bShared, bool bCheck
#if OSL_DEBUG_LEVEL > 0
                OUString aValue;
                if ( eSourceType == SC_CAT_CONTENT )
                    aValue = static_cast<const ScChangeActionContent*>(pSourceAction)->GetNewString( &m_aDocument );
                    aValue = static_cast<const ScChangeActionContent*>(pSourceAction)->GetNewString( m_pDocument.get() );
                SAL_WARN( "sc", aValue << " omitted");
#endif
            }
@@ -981,7 +981,7 @@ void ScDocShell::MergeDocument( ScDocument& rOtherDoc, bool bShared, bool bCheck

                            OSL_ENSURE( aSourceRange.aStart == aSourceRange.aEnd, "huch?" );
                            ScAddress aPos = aSourceRange.aStart;
                            OUString aValue = static_cast<const ScChangeActionContent*>(pSourceAction)->GetNewString( &m_aDocument );
                            OUString aValue = static_cast<const ScChangeActionContent*>(pSourceAction)->GetNewString( m_pDocument.get() );
                            ScMatrixMode eMatrix = ScMatrixMode::NONE;
                            const ScCellValue& rCell = static_cast<const ScChangeActionContent*>(pSourceAction)->GetNewCell();
                            if (rCell.meType == CELLTYPE_FORMULA)
@@ -1012,7 +1012,7 @@ void ScDocShell::MergeDocument( ScDocument& rOtherDoc, bool bShared, bool bCheck
                        case SC_CAT_INSERT_TABS :
                        {
                            OUString aName;
                            m_aDocument.CreateValidTabName( aName );
                            m_pDocument->CreateValidTabName( aName );
                            (void)GetDocFunc().InsertTable( aSourceRange.aStart.Tab(), aName, true, false );
                        }
                        break;
@@ -1140,7 +1140,7 @@ bool ScDocShell::MergeSharedDocument( ScDocShell* pSharedDocShell )
        return false;
    }

    ScChangeTrack* pThisTrack = m_aDocument.GetChangeTrack();
    ScChangeTrack* pThisTrack = m_pDocument->GetChangeTrack();
    if ( !pThisTrack )
    {
        return false;
@@ -1156,7 +1156,7 @@ bool ScDocShell::MergeSharedDocument( ScDocShell* pSharedDocShell )
    // reset show changes
    ScChangeViewSettings aChangeViewSet;
    aChangeViewSet.SetShowChanges( false );
    m_aDocument.SetChangeViewSettings( aChangeViewSet );
    m_pDocument->SetChangeViewSettings( aChangeViewSet );

    // find first merge action in this document
    bool bIgnore100Sec = !pThisTrack->IsTimeNanoSeconds() || !pSharedTrack->IsTimeNanoSeconds();
@@ -1176,13 +1176,13 @@ bool ScDocShell::MergeSharedDocument( ScDocShell* pSharedDocShell )
            sal_uLong nActStartShared = pSharedAction->GetActionNumber();
            sal_uLong nActEndShared = pSharedTrack->GetActionMax();
            std::optional<ScDocument> pTmpDoc(std::in_place);
            for ( sal_Int32 nIndex = 0; nIndex < m_aDocument.GetTableCount(); ++nIndex )
            for ( sal_Int32 nIndex = 0; nIndex < m_pDocument->GetTableCount(); ++nIndex )
            {
                OUString sTabName;
                pTmpDoc->CreateValidTabName( sTabName );
                pTmpDoc->InsertTab( SC_TAB_APPEND, sTabName );
            }
            m_aDocument.GetChangeTrack()->Clone( &*pTmpDoc );
            m_pDocument->GetChangeTrack()->Clone( &*pTmpDoc );
            ScChangeActionMergeMap aOwnInverseMergeMap;
            pSharedDocShell->MergeDocument( *pTmpDoc, true, true, 0, &aOwnInverseMergeMap, true );
            pTmpDoc.reset();
@@ -1224,7 +1224,7 @@ bool ScDocShell::MergeSharedDocument( ScDocShell* pSharedDocShell )

            // clone change track for merging into own document
            pTmpDoc.emplace();
            for ( sal_Int32 nIndex = 0; nIndex < m_aDocument.GetTableCount(); ++nIndex )
            for ( sal_Int32 nIndex = 0; nIndex < m_pDocument->GetTableCount(); ++nIndex )
            {
                OUString sTabName;
                pTmpDoc->CreateValidTabName( sTabName );
@@ -1269,7 +1269,7 @@ bool ScDocShell::MergeSharedDocument( ScDocShell* pSharedDocShell )
            aChangeViewSet.SetShowAccepted( true );
            aChangeViewSet.SetHasActionRange();
            aChangeViewSet.SetTheActionRange( nStartShared, nEndShared );
            m_aDocument.SetChangeViewSettings( aChangeViewSet );
            m_pDocument->SetChangeViewSettings( aChangeViewSet );

            // merge own changes back into own document
            sal_uLong nStartOwn = nEndShared + 1;
@@ -1312,7 +1312,7 @@ bool ScDocShell::MergeSharedDocument( ScDocShell* pSharedDocShell )
            aChangeViewSet.SetShowAccepted( true );
            aChangeViewSet.SetHasActionRange();
            aChangeViewSet.SetTheActionRange( nStartShared, nEndShared );
            m_aDocument.SetChangeViewSettings( aChangeViewSet );
            m_pDocument->SetChangeViewSettings( aChangeViewSet );
        }

        // update view
diff --git a/sc/source/ui/docshell/docsh4.cxx b/sc/source/ui/docshell/docsh4.cxx
index edea61f..480e99b 100644
--- a/sc/source/ui/docshell/docsh4.cxx
+++ b/sc/source/ui/docshell/docsh4.cxx
@@ -170,7 +170,7 @@ ScLkUpdMode ScDocShell::GetLinkUpdateModeState() const

void ScDocShell::AllowLinkUpdate()
{
    m_aDocument.SetLinkFormulaNeedingCheck(false);
    m_pDocument->SetLinkFormulaNeedingCheck(false);
    getEmbeddedObjectContainer().setUserAllowsLinkUpdate(true);
}

@@ -180,21 +180,21 @@ void ScDocShell::ReloadAllLinks()

    ReloadTabLinks();
    weld::Window *pDialogParent = GetActiveDialogParent();
    m_aDocument.UpdateExternalRefLinks(pDialogParent);
    m_pDocument->UpdateExternalRefLinks(pDialogParent);

    bool bAnyDde = m_aDocument.GetDocLinkManager().updateDdeOrOleOrWebServiceLinks(pDialogParent);
    bool bAnyDde = m_pDocument->GetDocLinkManager().updateDdeOrOleOrWebServiceLinks(pDialogParent);

    if (bAnyDde)
    {
        //  calculate formulas and paint like in the TrackTimeHdl
        m_aDocument.TrackFormulas();
        m_pDocument->TrackFormulas();
        Broadcast(SfxHint(SfxHintId::ScDataChanged));

        //  Should FID_DATACHANGED become asynchronous some time
        //  (e.g., with Invalidate at Window), an update needs to be forced here.
    }

    m_aDocument.UpdateAreaLinks();
    m_pDocument->UpdateAreaLinks();
}

IMPL_LINK_NOARG( ScDocShell, ReloadAllLinksHdl, weld::Button&, void )
@@ -227,7 +227,7 @@ void ScDocShell::Execute( SfxRequest& rReq )
{
    const SfxItemSet* pReqArgs = rReq.GetArgs();
    SfxBindings* pBindings = GetViewBindings();
    bool bUndo (m_aDocument.IsUndoEnabled());
    bool bUndo (m_pDocument->IsUndoEnabled());

    sal_uInt16 nSlot = rReq.GetSlot();
    switch ( nSlot )
@@ -248,13 +248,13 @@ void ScDocShell::Execute( SfxRequest& rReq )
                SCROW nRow = static_cast<const SfxInt32Item*>(pRowItem)->GetValue() - 1;
                SCTAB nTab = static_cast<const SfxInt16Item*>(pTabItem)->GetValue() - 1;

                SCTAB nTabCount = m_aDocument.GetTableCount();
                if ( m_aDocument.ValidCol(nCol) && m_aDocument.ValidRow(nRow) && ValidTab(nTab,nTabCount) )
                SCTAB nTabCount = m_pDocument->GetTableCount();
                if ( m_pDocument->ValidCol(nCol) && m_pDocument->ValidRow(nRow) && ValidTab(nTab,nTabCount) )
                {
                    if ( m_aDocument.IsBlockEditable( nTab, nCol,nRow, nCol, nRow ) )
                    if ( m_pDocument->IsBlockEditable( nTab, nCol,nRow, nCol, nRow ) )
                    {
                        OUString aVal = static_cast<const SfxStringItem*>(pTextItem)->GetValue();
                        m_aDocument.SetString( nCol, nRow, nTab, aVal );
                        m_pDocument->SetString( nCol, nRow, nTab, aVal );

                        PostPaintCell( nCol, nRow, nTab );
                        SetDocumentModified();
@@ -303,11 +303,11 @@ void ScDocShell::Execute( SfxRequest& rReq )
                bool bMakeArea = false;
                if (bIsNewArea)
                {
                    ScDBCollection* pDBColl = m_aDocument.GetDBCollection();
                    ScDBCollection* pDBColl = m_pDocument->GetDBCollection();
                    if ( !pDBColl || !pDBColl->getNamedDBs().findByUpperName(ScGlobal::getCharClass().uppercase(sTarget)) )
                    {
                        ScAddress aPos;
                        if ( aPos.Parse( sTarget, m_aDocument, m_aDocument.GetAddressConvention() ) & ScRefFlags::VALID )
                        if ( aPos.Parse( sTarget, *m_pDocument, m_pDocument->GetAddressConvention() ) & ScRefFlags::VALID )
                        {
                            bMakeArea = true;
                            if (bUndo)
@@ -426,13 +426,13 @@ void ScDocShell::Execute( SfxRequest& rReq )

                    //! limit always or not at all ???
                    if (!bMultiRange)
                        m_aDocument.LimitChartArea( nTab, nCol1,nRow1, nCol2,nRow2 );
                        m_pDocument->LimitChartArea( nTab, nCol1,nRow1, nCol2,nRow2 );

                                        // Dialog for column/row headers
                    bool bOk = true;
                    if ( !bAddRange && ( !bColInit || !bRowInit ) )
                    {
                        ScChartPositioner aChartPositioner( m_aDocument, nTab, nCol1,nRow1, nCol2,nRow2 );
                        ScChartPositioner aChartPositioner( *m_pDocument, nTab, nCol1,nRow1, nCol2,nRow2 );
                        if (!bColInit)
                            bColHeaders = aChartPositioner.HasColHeaders();
                        if (!bRowInit)
@@ -463,7 +463,7 @@ void ScDocShell::Execute( SfxRequest& rReq )
                                    std::make_unique<ScUndoChartData>( this, aChartName, aRangeListRef,
                                                            bColHeaders, bRowHeaders, bAddRange ) );
                            }
                            m_aDocument.UpdateChartArea( aChartName, aRangeListRef,
                            m_pDocument->UpdateChartArea( aChartName, aRangeListRef,
                                                        bColHeaders, bRowHeaders, bAddRange );
                        }
                        else
@@ -475,7 +475,7 @@ void ScDocShell::Execute( SfxRequest& rReq )
                                    std::make_unique<ScUndoChartData>( this, aChartName, aNewRange,
                                                            bColHeaders, bRowHeaders, bAddRange ) );
                            }
                            m_aDocument.UpdateChartArea( aChartName, aNewRange,
                            m_pDocument->UpdateChartArea( aChartName, aNewRange,
                                                        bColHeaders, bRowHeaders, bAddRange );
                        }
                    }
@@ -499,8 +499,8 @@ void ScDocShell::Execute( SfxRequest& rReq )
                if ( pReqArgs && SfxItemState::SET == pReqArgs->GetItemState( nSlot, true, &pItem ) )
                    bNewVal = static_cast<const SfxBoolItem*>(pItem)->GetValue();
                else
                    bNewVal = !m_aDocument.GetAutoCalc();     // Toggle for menu
                m_aDocument.SetAutoCalc( bNewVal );
                    bNewVal = !m_pDocument->GetAutoCalc();     // Toggle for menu
                m_pDocument->SetAutoCalc( bNewVal );
                SetDocumentModified();
                if (pBindings)
                {
@@ -561,7 +561,7 @@ void ScDocShell::Execute( SfxRequest& rReq )
                //  Is called after loading if there are DB areas with omitted data

                bool bDone = false;
                ScDBCollection* pDBColl = m_aDocument.GetDBCollection();
                ScDBCollection* pDBColl = m_pDocument->GetDBCollection();

                if ((m_nCanUpdate != css::document::UpdateDocMode::NO_UPDATE) &&
                   (m_nCanUpdate != css::document::UpdateDocMode::QUIET_UPDATE))
@@ -623,7 +623,7 @@ void ScDocShell::Execute( SfxRequest& rReq )
                    //  if not, but then update the dependent formulas
                    //! also for individual ranges, which cannot be updated

                    m_aDocument.CalcAll();        //! only for the dependent
                    m_pDocument->CalcAll();        //! only for the dependent
                    PostDataChanged();
                }

@@ -725,7 +725,7 @@ void ScDocShell::Execute( SfxRequest& rReq )
        case SID_DOCUMENT_COMPARE:
            {
                bool bDo = true;
                ScChangeTrack* pChangeTrack = m_aDocument.GetChangeTrack();
                ScChangeTrack* pChangeTrack = m_pDocument->GetChangeTrack();
                if ( pChangeTrack && !m_pImpl->bIgnoreLostRedliningWarning )
                {
                    if ( nSlot == SID_DOCUMENT_COMPARE )
@@ -823,7 +823,7 @@ void ScDocShell::Execute( SfxRequest& rReq )

                if ( !pOtherDocSh->GetError() )                 // only errors
                {
                    bool bHadTrack = ( m_aDocument.GetChangeTrack() != nullptr );
                    bool bHadTrack = ( m_pDocument->GetChangeTrack() != nullptr );
#if HAVE_FEATURE_MULTIUSER_ENVIRONMENT
                    sal_uLong nStart = 0;
                    if ( nSlot == SID_DOCUMENT_MERGE && pChangeTrack )
@@ -856,12 +856,12 @@ void ScDocShell::Execute( SfxRequest& rReq )

                    if (!bHadTrack)         //  newly turned on -> show as well
                    {
                        ScChangeViewSettings* pOldSet = m_aDocument.GetChangeViewSettings();
                        ScChangeViewSettings* pOldSet = m_pDocument->GetChangeViewSettings();
                        if ( !pOldSet || !pOldSet->ShowChanges() )
                        {
                            ScChangeViewSettings aChangeViewSet;
                            aChangeViewSet.SetShowChanges(true);
                            m_aDocument.SetChangeViewSettings(aChangeViewSet);
                            m_pDocument->SetChangeViewSettings(aChangeViewSet);
                        }
                    }
#if HAVE_FEATURE_MULTIUSER_ENVIRONMENT
@@ -876,7 +876,7 @@ void ScDocShell::Execute( SfxRequest& rReq )
                            aChangeViewSet.SetShowAccepted( true );
                            aChangeViewSet.SetHasActionRange();
                            aChangeViewSet.SetTheActionRange( nStart, nEnd );
                            m_aDocument.SetChangeViewSettings( aChangeViewSet );
                            m_pDocument->SetChangeViewSettings( aChangeViewSet );

                            // update view
                            PostPaintExtras();
@@ -899,7 +899,7 @@ void ScDocShell::Execute( SfxRequest& rReq )
                    {
                        const OUString& aName = pStringItem->GetValue();
                        SCTAB nTab;
                        if (m_aDocument.GetTable( aName, nTab ))
                        if (m_pDocument->GetTable( aName, nTab ))
                        {
                            //  move DeleteTable from viewfunc to docfunc!

@@ -927,14 +927,14 @@ void ScDocShell::Execute( SfxRequest& rReq )
                    {
                        OUString aName = pStringItem->GetValue();
                        SCTAB nTab;
                        if (m_aDocument.GetTable( aName, nTab ))
                        if (m_pDocument->GetTable( aName, nTab ))
                        {
                            if (m_aDocument.IsScenario(nTab))
                            if (m_pDocument->IsScenario(nTab))
                            {
                                OUString aComment;
                                Color aColor;
                                ScScenarioFlags nFlags;
                                m_aDocument.GetScenarioData( nTab, aComment, aColor, nFlags );
                                m_pDocument->GetScenarioData( nTab, aComment, aColor, nFlags );

                                // Determine if the Sheet that the Scenario was created on
                                // is protected. But first we need to find that Sheet.
@@ -944,8 +944,8 @@ void ScDocShell::Execute( SfxRequest& rReq )
                                {
                                    nActualTab--;
                                }
                                while(m_aDocument.IsScenario(nActualTab));
                                bool bSheetProtected = m_aDocument.IsTabProtected(nActualTab);
                                while(m_pDocument->IsScenario(nActualTab));
                                bool bSheetProtected = m_pDocument->IsTabProtected(nActualTab);

                                ScAbstractDialogFactory* pFact = ScAbstractDialogFactory::Create();

@@ -975,9 +975,9 @@ void ScDocShell::Execute( SfxRequest& rReq )
                    // set always to DocOptions, so that it is also saved for S050
                    // (and all inquiries run up until now on it as well).
                    // SetDocOptions propagates that to the NumberFormatter
                    ScDocOptions aDocOpt( m_aDocument.GetDocOptions() );
                    ScDocOptions aDocOpt( m_pDocument->GetDocOptions() );
                    aDocOpt.SetYear2000( nY2k );
                    m_aDocument.SetDocOptions( aDocOpt );
                    m_pDocument->SetDocOptions( aDocOpt );
                    // the FormShell shall notice it as well
                    ScTabViewShell* pSh = GetBestViewShell();
                    if ( pSh )
@@ -1398,7 +1398,7 @@ void UpdateAcceptChangesDialog()
bool ScDocShell::ExecuteChangeProtectionDialog( bool bJustQueryIfProtected )
{
    bool bDone = false;
    ScChangeTrack* pChangeTrack = m_aDocument.GetChangeTrack();
    ScChangeTrack* pChangeTrack = m_pDocument->GetChangeTrack();
    if ( pChangeTrack )
    {
        bool bProtected = pChangeTrack->IsProtected();
@@ -1459,12 +1459,12 @@ bool ScDocShell::ExecuteChangeProtectionDialog( bool bJustQueryIfProtected )

void ScDocShell::DoRecalc( bool bApi )
{
    if (m_aDocument.IsInDocShellRecalc())
    if (m_pDocument->IsInDocShellRecalc())
    {
        SAL_WARN("sc","ScDocShell::DoRecalc tries re-entering while in Recalc; probably Forms->BASIC->Dispatcher.");
        return;
    }
    ScDocShellRecalcGuard aGuard(m_aDocument);
    ScDocShellRecalcGuard aGuard(*m_pDocument);
    bool bDone = false;
    ScTabViewShell* pSh = GetBestViewShell();
    ScInputHandler* pHdl = ( pSh ? SC_MOD()->GetInputHdl( pSh ) : nullptr );
@@ -1488,20 +1488,20 @@ void ScDocShell::DoRecalc( bool bApi )
    if ( pHdl )
    {
        // tdf97897 set current cell to Dirty to force recalculation of cell
        ScFormulaCell* pFC = m_aDocument.GetFormulaCell( pHdl->GetCursorPos());
        ScFormulaCell* pFC = m_pDocument->GetFormulaCell( pHdl->GetCursorPos());
        if (pFC)
            pFC->SetDirty();
    }
    m_aDocument.CalcFormulaTree();
    m_pDocument->CalcFormulaTree();
    if ( pSh )
        pSh->UpdateCharts(true);

    m_aDocument.BroadcastUno( SfxHint( SfxHintId::DataChanged ) );
    m_pDocument->BroadcastUno( SfxHint( SfxHintId::DataChanged ) );

    //  If there are charts, then paint everything, so that PostDataChanged
    //  and the charts do not come one after the other and parts are painted twice.

    ScChartListenerCollection* pCharts = m_aDocument.GetChartListenerCollection();
    ScChartListenerCollection* pCharts = m_pDocument->GetChartListenerCollection();
    if ( pCharts && pCharts->hasListeners() )
        PostPaintGridAll();
    else
@@ -1510,13 +1510,13 @@ void ScDocShell::DoRecalc( bool bApi )

void ScDocShell::DoHardRecalc()
{
    if (m_aDocument.IsInDocShellRecalc())
    if (m_pDocument->IsInDocShellRecalc())
    {
        SAL_WARN("sc","ScDocShell::DoHardRecalc tries re-entering while in Recalc; probably Forms->BASIC->Dispatcher.");
        return;
    }
    auto start = std::chrono::steady_clock::now();
    ScDocShellRecalcGuard aGuard(m_aDocument);
    ScDocShellRecalcGuard aGuard(*m_pDocument);
    weld::WaitObject aWaitObj( GetActiveDialogParent() );
    ScTabViewShell* pSh = GetBestViewShell();
    if ( pSh )
@@ -1524,27 +1524,27 @@ void ScDocShell::DoHardRecalc()
        ScTabView::UpdateInputLine();     // InputEnterHandler
        pSh->UpdateInputHandler();
    }
    m_aDocument.CalcAll();
    m_pDocument->CalcAll();
    GetDocFunc().DetectiveRefresh();    // creates own Undo
    if ( pSh )
        pSh->UpdateCharts(true);

    // set notification flags for "calculate" event (used in SfxHintId::DataChanged broadcast)
    // (might check for the presence of any formulas on each sheet)
    SCTAB nTabCount = m_aDocument.GetTableCount();
    if (m_aDocument.HasAnySheetEventScript( ScSheetEventId::CALCULATE, true )) // search also for VBA handler
    SCTAB nTabCount = m_pDocument->GetTableCount();
    if (m_pDocument->HasAnySheetEventScript( ScSheetEventId::CALCULATE, true )) // search also for VBA handler
        for (SCTAB nTab=0; nTab<nTabCount; nTab++)
            m_aDocument.SetCalcNotification(nTab);
            m_pDocument->SetCalcNotification(nTab);

    // CalcAll doesn't broadcast value changes, so SfxHintId::ScCalcAll is broadcasted globally
    // in addition to SfxHintId::DataChanged.
    m_aDocument.BroadcastUno( SfxHint( SfxHintId::ScCalcAll ) );
    m_aDocument.BroadcastUno( SfxHint( SfxHintId::DataChanged ) );
    m_pDocument->BroadcastUno( SfxHint( SfxHintId::ScCalcAll ) );
    m_pDocument->BroadcastUno( SfxHint( SfxHintId::DataChanged ) );

    // use hard recalc also to disable stream-copying of all sheets
    // (somewhat consistent with charts)
    for (SCTAB nTab=0; nTab<nTabCount; nTab++)
        m_aDocument.SetStreamValid(nTab, false);
        m_pDocument->SetStreamValid(nTab, false);

    PostPaintGridAll();
    auto end = std::chrono::steady_clock::now();
@@ -1553,7 +1553,7 @@ void ScDocShell::DoHardRecalc()

void ScDocShell::DoAutoStyle( const ScRange& rRange, const OUString& rStyle )
{
    ScStyleSheetPool* pStylePool = m_aDocument.GetStyleSheetPool();
    ScStyleSheetPool* pStylePool = m_pDocument->GetStyleSheetPool();
    ScStyleSheet* pStyleSheet =
        pStylePool->FindCaseIns( rStyle, SfxStyleFamily::Para );
    if (!pStyleSheet)
@@ -1569,8 +1569,8 @@ void ScDocShell::DoAutoStyle( const ScRange& rRange, const OUString& rStyle )
    SCROW nStartRow = rRange.aStart.Row();
    SCCOL nEndCol = rRange.aEnd.Col();
    SCROW nEndRow = rRange.aEnd.Row();
    m_aDocument.ApplyStyleAreaTab( nStartCol, nStartRow, nEndCol, nEndRow, nTab, *pStyleSheet );
    m_aDocument.ExtendMerge( nStartCol, nStartRow, nEndCol, nEndRow, nTab );
    m_pDocument->ApplyStyleAreaTab( nStartCol, nStartRow, nEndCol, nEndRow, nTab, *pStyleSheet );
    m_pDocument->ExtendMerge( nStartCol, nStartRow, nEndCol, nEndRow, nTab );
    PostPaint( nStartCol, nStartRow, nTab, nEndCol, nEndRow, nTab, PaintPartFlags::Grid );
}

@@ -1594,13 +1594,13 @@ void ScDocShell::NotifyStyle( const SfxStyleSheetHint& rHint )
                aOldName = pExtendedHint->GetOldName();

            if ( aNewName != aOldName )
                m_aDocument.RenamePageStyleInUse( aOldName, aNewName );
                m_pDocument->RenamePageStyleInUse( aOldName, aNewName );

            SCTAB nTabCount = m_aDocument.GetTableCount();
            SCTAB nTabCount = m_pDocument->GetTableCount();
            for (SCTAB nTab=0; nTab<nTabCount; nTab++)
                if (m_aDocument.GetPageStyle(nTab) == aNewName)   // already adjusted to new
                if (m_pDocument->GetPageStyle(nTab) == aNewName)   // already adjusted to new
                {
                    m_aDocument.PageStyleModified( nTab, aNewName );
                    m_pDocument->PageStyleModified( nTab, aNewName );
                    ScPrintFunc aPrintFunc( this, GetPrinter(), nTab );
                    aPrintFunc.UpdatePages();
                }
@@ -1632,9 +1632,9 @@ void ScDocShell::NotifyStyle( const SfxStyleSheetHint& rHint )
                aOldName = pExtendedHint->GetOldName();
            if ( aNewName != aOldName )
            {
                for(SCTAB i = 0; i < m_aDocument.GetTableCount(); ++i)
                for(SCTAB i = 0; i < m_pDocument->GetTableCount(); ++i)
                {
                    ScConditionalFormatList* pList = m_aDocument.GetCondFormList(i);
                    ScConditionalFormatList* pList = m_pDocument->GetCondFormList(i);
                    if (pList)
                        pList->RenameCellStyle( aOldName,aNewName );
                }
@@ -1650,8 +1650,8 @@ void ScDocShell::NotifyStyle( const SfxStyleSheetHint& rHint )

void ScDocShell::SetPrintZoom( SCTAB nTab, sal_uInt16 nScale, sal_uInt16 nPages )
{
    OUString aStyleName = m_aDocument.GetPageStyle( nTab );
    ScStyleSheetPool* pStylePool = m_aDocument.GetStyleSheetPool();
    OUString aStyleName = m_pDocument->GetPageStyle( nTab );
    ScStyleSheetPool* pStylePool = m_pDocument->GetStyleSheetPool();
    SfxStyleSheetBase* pStyleSheet = pStylePool->Find( aStyleName, SfxStyleFamily::Page );
    OSL_ENSURE( pStyleSheet, "PageStyle not found" );
    if ( !pStyleSheet )
@@ -1660,7 +1660,7 @@ void ScDocShell::SetPrintZoom( SCTAB nTab, sal_uInt16 nScale, sal_uInt16 nPages 
    ScDocShellModificator aModificator( *this );

    SfxItemSet& rSet = pStyleSheet->GetItemSet();
    const bool bUndo(m_aDocument.IsUndoEnabled());
    const bool bUndo(m_pDocument->IsUndoEnabled());
    if (bUndo)
    {
        sal_uInt16 nOldScale = rSet.Get(ATTR_PAGE_SCALE).GetValue();
@@ -1686,8 +1686,8 @@ bool ScDocShell::AdjustPrintZoom( const ScRange& rRange )
    bool bChange = false;
    SCTAB nTab = rRange.aStart.Tab();

    OUString aStyleName = m_aDocument.GetPageStyle( nTab );
    ScStyleSheetPool* pStylePool = m_aDocument.GetStyleSheetPool();
    OUString aStyleName = m_pDocument->GetPageStyle( nTab );
    ScStyleSheetPool* pStylePool = m_pDocument->GetStyleSheetPool();
    SfxStyleSheetBase* pStyleSheet = pStylePool->Find( aStyleName, SfxStyleFamily::Page );
    OSL_ENSURE( pStyleSheet, "PageStyle not found" );
    if ( pStyleSheet )
@@ -1696,8 +1696,8 @@ bool ScDocShell::AdjustPrintZoom( const ScRange& rRange )
        bool bHeaders = rSet.Get(ATTR_PAGE_HEADERS).GetValue();
        sal_uInt16 nOldScale = rSet.Get(ATTR_PAGE_SCALE).GetValue();
        sal_uInt16 nOldPages = rSet.Get(ATTR_PAGE_SCALETOPAGES).GetValue();
        const ScRange* pRepeatCol = m_aDocument.GetRepeatColRange( nTab );
        const ScRange* pRepeatRow = m_aDocument.GetRepeatRowRange( nTab );
        const ScRange* pRepeatCol = m_pDocument->GetRepeatColRange( nTab );
        const ScRange* pRepeatRow = m_pDocument->GetRepeatRowRange( nTab );

        //  calculate needed scaling for selection

@@ -1711,14 +1711,14 @@ bool ScDocShell::AdjustPrintZoom( const ScRange& rRange )
        if ( pRepeatCol && nStartCol >= pRepeatCol->aStart.Col() )
        {
            for (SCCOL i=pRepeatCol->aStart.Col(); i<=pRepeatCol->aEnd.Col(); i++ )
                nBlkTwipsX += m_aDocument.GetColWidth( i, nTab );
                nBlkTwipsX += m_pDocument->GetColWidth( i, nTab );
            if ( nStartCol <= pRepeatCol->aEnd.Col() )
                nStartCol = pRepeatCol->aEnd.Col() + 1;
        }
        // legacy compilers' own scope for i
        {
            for ( SCCOL i=nStartCol; i<=nEndCol; i++ )
                nBlkTwipsX += m_aDocument.GetColWidth( i, nTab );
                nBlkTwipsX += m_pDocument->GetColWidth( i, nTab );
        }

        tools::Long nBlkTwipsY = 0;
@@ -1728,12 +1728,12 @@ bool ScDocShell::AdjustPrintZoom( const ScRange& rRange )
        SCROW nEndRow = rRange.aEnd.Row();
        if ( pRepeatRow && nStartRow >= pRepeatRow->aStart.Row() )
        {
            nBlkTwipsY += m_aDocument.GetRowHeight( pRepeatRow->aStart.Row(),
            nBlkTwipsY += m_pDocument->GetRowHeight( pRepeatRow->aStart.Row(),
                    pRepeatRow->aEnd.Row(), nTab );
            if ( nStartRow <= pRepeatRow->aEnd.Row() )
                nStartRow = pRepeatRow->aEnd.Row() + 1;
        }
        nBlkTwipsY += m_aDocument.GetRowHeight( nStartRow, nEndRow, nTab );
        nBlkTwipsY += m_pDocument->GetRowHeight( nStartRow, nEndRow, nTab );

        Size aPhysPage;
        tools::Long nHdr, nFtr;
@@ -1764,11 +1764,11 @@ void ScDocShell::PageStyleModified( std::u16string_view rStyleName, bool bApi )
{
    ScDocShellModificator aModificator( *this );

    SCTAB nTabCount = m_aDocument.GetTableCount();
    SCTAB nTabCount = m_pDocument->GetTableCount();
    SCTAB nUseTab = MAXTAB+1;
    for (SCTAB nTab=0; nTab<nTabCount && nUseTab>MAXTAB; nTab++)
        if ( m_aDocument.GetPageStyle(nTab) == rStyleName &&
                ( !bApi || m_aDocument.GetPageSize(nTab).Width() ) )
        if ( m_pDocument->GetPageStyle(nTab) == rStyleName &&
                ( !bApi || m_pDocument->GetPageSize(nTab).Width() ) )
            nUseTab = nTab;
                                // at bApi only if breaks already shown

@@ -1815,8 +1815,8 @@ void ScDocShell::ExecutePageStyle( const SfxViewShell& rCaller,
            {
                if ( pReqArgs == nullptr )
                {
                    OUString aOldName = m_aDocument.GetPageStyle( nCurTab );
                    ScStyleSheetPool* pStylePool = m_aDocument.GetStyleSheetPool();
                    OUString aOldName = m_pDocument->GetPageStyle( nCurTab );
                    ScStyleSheetPool* pStylePool = m_pDocument->GetStyleSheetPool();
                    SfxStyleSheetBase* pStyleSheet
                        = pStylePool->Find( aOldName, SfxStyleFamily::Page );

@@ -1825,7 +1825,7 @@ void ScDocShell::ExecutePageStyle( const SfxViewShell& rCaller,
                    if ( pStyleSheet )
                    {
                        ScStyleSaveData aOldData;
                        const bool bUndo(m_aDocument.IsUndoEnabled());
                        const bool bUndo(m_pDocument->IsUndoEnabled());
                        if (bUndo)
                            aOldData.InitFromStyle( pStyleSheet );

@@ -1847,7 +1847,7 @@ void ScDocShell::ExecutePageStyle( const SfxViewShell& rCaller,

                                OUString aNewName = pStyleSheet->GetName();
                                if ( aNewName != aOldName &&
                                    m_aDocument.RenamePageStyleInUse( aOldName, aNewName ) )
                                    m_pDocument->RenamePageStyleInUse( aOldName, aNewName ) )
                                {
                                    SfxBindings* pBindings = GetViewBindings();
                                    if (pBindings)
@@ -1858,7 +1858,7 @@ void ScDocShell::ExecutePageStyle( const SfxViewShell& rCaller,
                                }

                                if ( pOutSet )
                                    m_aDocument.ModifyStyleSheet( *pStyleSheet, *pOutSet );
                                    m_pDocument->ModifyStyleSheet( *pStyleSheet, *pOutSet );

                                // memorizing for GetState():
                                GetPageOnFromPageStyleSet( &rStyleSet, nCurTab, m_bHeaderOn, m_bFooterOn );
@@ -1887,10 +1887,10 @@ void ScDocShell::ExecutePageStyle( const SfxViewShell& rCaller,
            {
                if ( pReqArgs == nullptr )
                {
                    OUString aStr( m_aDocument.GetPageStyle( nCurTab ) );
                    OUString aStr( m_pDocument->GetPageStyle( nCurTab ) );

                    ScStyleSheetPool* pStylePool
                        = m_aDocument.GetStyleSheetPool();
                        = m_pDocument->GetStyleSheetPool();

                    SfxStyleSheetBase* pStyleSheet
                        = pStylePool->Find( aStr, SfxStyleFamily::Page );
@@ -2004,7 +2004,7 @@ void ScDocShell::ExecutePageStyle( const SfxViewShell& rCaller,
                                const SfxItemSet* pOutSet = pDlg->GetOutputItemSet();

                                if ( pOutSet )
                                    m_aDocument.ModifyStyleSheet( *pStyleSheet, *pOutSet );
                                    m_pDocument->ModifyStyleSheet( *pStyleSheet, *pOutSet );

                                SetDocumentModified();
                                xRequest->Done();
@@ -2031,13 +2031,13 @@ void ScDocShell::GetStatePageStyle( SfxItemSet&     rSet,
        switch (nWhich)
        {
            case SID_STATUS_PAGESTYLE:
                rSet.Put( SfxStringItem( nWhich, m_aDocument.GetPageStyle( nCurTab ) ) );
                rSet.Put( SfxStringItem( nWhich, m_pDocument->GetPageStyle( nCurTab ) ) );
                break;

            case SID_HFEDIT:
                {
                    OUString            aStr        = m_aDocument.GetPageStyle( nCurTab );
                    ScStyleSheetPool*   pStylePool  = m_aDocument.GetStyleSheetPool();
                    OUString            aStr        = m_pDocument->GetPageStyle( nCurTab );
                    ScStyleSheetPool*   pStylePool  = m_pDocument->GetStyleSheetPool();
                    SfxStyleSheetBase*  pStyleSheet = pStylePool->Find( aStr, SfxStyleFamily::Page );

                    OSL_ENSURE( pStyleSheet, "PageStyle not found! :-/" );
@@ -2074,10 +2074,10 @@ void ScDocShell::GetState( SfxItemSet &rSet )
        switch (nWhich)
        {
            case FID_AUTO_CALC:
                if ( m_aDocument.GetHardRecalcState() != ScDocument::HardRecalcState::OFF )
                if ( m_pDocument->GetHardRecalcState() != ScDocument::HardRecalcState::OFF )
                    rSet.DisableItem( nWhich );
                else
                    rSet.Put( SfxBoolItem( nWhich, m_aDocument.GetAutoCalc() ) );
                    rSet.Put( SfxBoolItem( nWhich, m_pDocument->GetAutoCalc() ) );
                break;

            case FID_CHG_RECORD:
@@ -2085,12 +2085,12 @@ void ScDocShell::GetState( SfxItemSet &rSet )
                    rSet.DisableItem( nWhich );
                else
                    rSet.Put( SfxBoolItem( nWhich,
                        m_aDocument.GetChangeTrack() != nullptr ) );
                        m_pDocument->GetChangeTrack() != nullptr ) );
                break;

            case SID_CHG_PROTECT:
                {
                    ScChangeTrack* pChangeTrack = m_aDocument.GetChangeTrack();
                    ScChangeTrack* pChangeTrack = m_pDocument->GetChangeTrack();
                    if ( pChangeTrack && !IsDocShared() )
                        rSet.Put( SfxBoolItem( nWhich,
                            pChangeTrack->IsProtected() ) );
@@ -2113,12 +2113,12 @@ void ScDocShell::GetState( SfxItemSet &rSet )
            //  always enabled because of another bug.

            case SID_TABLES_COUNT:
                rSet.Put( SfxInt16Item( nWhich, m_aDocument.GetTableCount() ) );
                rSet.Put( SfxInt16Item( nWhich, m_pDocument->GetTableCount() ) );
                break;

            case SID_ATTR_YEAR2000 :
                rSet.Put( SfxUInt16Item( nWhich,
                    m_aDocument.GetDocOptions().GetYear2000() ) );
                    m_pDocument->GetDocOptions().GetYear2000() ) );
            break;

            case SID_SHARE_DOC:
@@ -2172,8 +2172,8 @@ void ScDocShell::GetState( SfxItemSet &rSet )
void ScDocShell::Draw( OutputDevice* pDev, const JobSetup & /* rSetup */, sal_uInt16 nAspect )
{

    SCTAB nVisTab = m_aDocument.GetVisibleTab();
    if (!m_aDocument.HasTable(nVisTab))
    SCTAB nVisTab = m_pDocument->GetVisibleTab();
    if (!m_pDocument->HasTable(nVisTab))
        return;

    vcl::text::ComplexTextLayoutFlags nOldLayoutMode = pDev->GetLayoutMode();
@@ -2186,7 +2186,7 @@ void ScDocShell::Draw( OutputDevice* pDev, const JobSetup & /* rSetup */, sal_uI
        aTmpData.SetTabNo(nVisTab);
        SnapVisArea( aBoundRect );
        aTmpData.SetScreen( aBoundRect );
        ScPrintFunc::DrawToDev( m_aDocument, pDev, 1.0, aBoundRect, &aTmpData, true );
        ScPrintFunc::DrawToDev( *m_pDocument, pDev, 1.0, aBoundRect, &aTmpData, true );
    }
    else
    {
@@ -2195,10 +2195,10 @@ void ScDocShell::Draw( OutputDevice* pDev, const JobSetup & /* rSetup */, sal_uI
        ScViewData aTmpData( *this, nullptr );
        aTmpData.SetTabNo(nVisTab);
        SnapVisArea( aNewArea );
        if ( aNewArea != aOldArea && (m_aDocument.GetPosLeft() > 0 || m_aDocument.GetPosTop() > 0) )
        if ( aNewArea != aOldArea && (m_pDocument->GetPosLeft() > 0 || m_pDocument->GetPosTop() > 0) )
            SfxObjectShell::SetVisArea( aNewArea );
        aTmpData.SetScreen( aNewArea );
        ScPrintFunc::DrawToDev( m_aDocument, pDev, 1.0, aNewArea, &aTmpData, true );
        ScPrintFunc::DrawToDev( *m_pDocument, pDev, 1.0, aNewArea, &aTmpData, true );
    }

    pDev->SetLayoutMode( nOldLayoutMode );
@@ -2216,13 +2216,13 @@ tools::Rectangle ScDocShell::GetVisArea( sal_uInt16 nAspect ) const

    if( nAspect == ASPECT_THUMBNAIL )
    {
        SCTAB nVisTab = m_aDocument.GetVisibleTab();
        if (!m_aDocument.HasTable(nVisTab))
        SCTAB nVisTab = m_pDocument->GetVisibleTab();
        if (!m_pDocument->HasTable(nVisTab))
        {
            nVisTab = 0;
            const_cast<ScDocShell*>(this)->m_aDocument.SetVisibleTab(nVisTab);
            const_cast<ScDocShell*>(this)->m_pDocument->SetVisibleTab(nVisTab);
        }
        Size aSize = m_aDocument.GetPageSize(nVisTab);
        Size aSize = m_pDocument->GetPageSize(nVisTab);
        const tools::Long SC_PREVIEW_SIZE_X = 10000;
        const tools::Long SC_PREVIEW_SIZE_Y = 12400;
        tools::Rectangle aArea( 0,0, SC_PREVIEW_SIZE_X, SC_PREVIEW_SIZE_Y);
@@ -2232,7 +2232,7 @@ tools::Rectangle ScDocShell::GetVisArea( sal_uInt16 nAspect ) const
            aArea.SetBottom( SC_PREVIEW_SIZE_X );
        }

        bool bNegativePage = m_aDocument.IsNegativePage( m_aDocument.GetVisibleTab() );
        bool bNegativePage = m_pDocument->IsNegativePage( m_pDocument->GetVisibleTab() );
        if ( bNegativePage )
            ScDrawLayer::MirrorRectRTL( aArea );
        SnapVisArea( aArea );
@@ -2242,24 +2242,24 @@ tools::Rectangle ScDocShell::GetVisArea( sal_uInt16 nAspect ) const
    {
        //  fetch visarea like after loading

        SCTAB nVisTab = m_aDocument.GetVisibleTab();
        if (!m_aDocument.HasTable(nVisTab))
        SCTAB nVisTab = m_pDocument->GetVisibleTab();
        if (!m_pDocument->HasTable(nVisTab))
        {
            nVisTab = 0;
            const_cast<ScDocShell*>(this)->m_aDocument.SetVisibleTab(nVisTab);
            const_cast<ScDocShell*>(this)->m_pDocument->SetVisibleTab(nVisTab);
        }
        SCCOL nStartCol;
        SCROW nStartRow;
        m_aDocument.GetDataStart( nVisTab, nStartCol, nStartRow );
        m_pDocument->GetDataStart( nVisTab, nStartCol, nStartRow );
        SCCOL nEndCol;
        SCROW nEndRow;
        m_aDocument.GetPrintArea( nVisTab, nEndCol, nEndRow );
        m_pDocument->GetPrintArea( nVisTab, nEndCol, nEndRow );
        if (nStartCol>nEndCol)
            nStartCol = nEndCol;
        if (nStartRow>nEndRow)
            nStartRow = nEndRow;
        tools::Rectangle aNewArea = m_aDocument
                                .GetMMRect( nStartCol,nStartRow, nEndCol,nEndRow, nVisTab );
        tools::Rectangle aNewArea = m_pDocument
                                ->GetMMRect( nStartCol,nStartRow, nEndCol,nEndRow, nVisTab );
        return aNewArea;
    }
    else
@@ -2332,26 +2332,26 @@ tools::Long SnapVertical( const ScDocument& rDoc, SCTAB nTab, tools::Long nVal, 

void ScDocShell::SnapVisArea( tools::Rectangle& rRect ) const
{
    SCTAB nTab = m_aDocument.GetVisibleTab();
    SCTAB nTab = m_pDocument->GetVisibleTab();
    tools::Long nOrigTop = rRect.Top();
    tools::Long nOrigLeft = rRect.Left();
    bool bNegativePage = m_aDocument.IsNegativePage( nTab );
    bool bNegativePage = m_pDocument->IsNegativePage( nTab );
    if ( bNegativePage )
        ScDrawLayer::MirrorRectRTL( rRect );        // calculate with positive (LTR) values

    SCCOL nCol = m_aDocument.GetPosLeft();
    tools::Long nSetLeft = SnapHorizontal( m_aDocument, nTab, rRect.Left(), nCol );
    SCCOL nCol = m_pDocument->GetPosLeft();
    tools::Long nSetLeft = SnapHorizontal( *m_pDocument, nTab, rRect.Left(), nCol );
    rRect.SetLeft( nSetLeft );
    ++nCol;                                         // at least one column
    tools::Long nCorrectionLeft = (nOrigLeft == 0 && nCol > 0) ? nSetLeft : 0; // initial correction
    rRect.SetRight( SnapHorizontal( m_aDocument, nTab, rRect.Right() + nCorrectionLeft, nCol ));
    rRect.SetRight( SnapHorizontal( *m_pDocument, nTab, rRect.Right() + nCorrectionLeft, nCol ));

    SCROW nRow = m_aDocument.GetPosTop();
    tools::Long nSetTop = SnapVertical( m_aDocument, nTab, rRect.Top(), nRow );
    SCROW nRow = m_pDocument->GetPosTop();
    tools::Long nSetTop = SnapVertical( *m_pDocument, nTab, rRect.Top(), nRow );
    rRect.SetTop( nSetTop );
    ++nRow;                                         // at least one row
    tools::Long nCorrectionTop = (nOrigTop == 0 && nRow > 0) ? nSetTop : 0; // initial correction
    rRect.SetBottom( SnapVertical( m_aDocument, nTab, rRect.Bottom() + nCorrectionTop, nRow ));
    rRect.SetBottom( SnapVertical( *m_pDocument, nTab, rRect.Bottom() + nCorrectionTop, nRow ));

    if ( bNegativePage )
        ScDrawLayer::MirrorRectRTL( rRect );        // back to real rectangle
@@ -2364,9 +2364,9 @@ void ScDocShell::GetPageOnFromPageStyleSet( const SfxItemSet* pStyleSet,
{
    if ( !pStyleSet )
    {
        ScStyleSheetPool*  pStylePool  = m_aDocument.GetStyleSheetPool();
        ScStyleSheetPool*  pStylePool  = m_pDocument->GetStyleSheetPool();
        SfxStyleSheetBase* pStyleSheet = pStylePool->
                                            Find( m_aDocument.GetPageStyle( nCurTab ),
                                            Find( m_pDocument->GetPageStyle( nCurTab ),
                                                  SfxStyleFamily::Page );

        OSL_ENSURE( pStyleSheet, "PageStyle not found! :-/" );
@@ -2410,7 +2410,7 @@ bool ScDocShell::DdeGetData( const OUString& rItem,
                                        aFmtByte.getLength() + 1 );
            return true;
        }
        ScImportExport aObj( m_aDocument, rItem );
        ScImportExport aObj( *m_pDocument, rItem );
        if ( !aObj.IsRef() )
            return false;                           // invalid range

@@ -2438,7 +2438,7 @@ bool ScDocShell::DdeGetData( const OUString& rItem,
        return aObj.ExportData( rMimeType, rValue );
    }

    ScImportExport aObj( m_aDocument, rItem );
    ScImportExport aObj( *m_pDocument, rItem );
    aObj.SetExportTextOptions( ScExportTextOptions( ScExportTextOptions::ToSpace, 0, false ) );
    return aObj.IsRef() && aObj.ExportData( rMimeType, rValue );
}
@@ -2459,7 +2459,7 @@ bool ScDocShell::DdeSetData( const OUString& rItem,
            }
            return false;
        }
        ScImportExport aObj( m_aDocument, rItem );
        ScImportExport aObj( *m_pDocument, rItem );
        if( m_aDdeTextFmt[0] == 'F' )
            aObj.SetFormulas( true );
        if( m_aDdeTextFmt == "SYLK" ||
@@ -2491,7 +2491,7 @@ bool ScDocShell::DdeSetData( const OUString& rItem,

    //  named range?
    OUString aPos = rItem;
    ScRangeName* pRange = m_aDocument.GetRangeName();
    ScRangeName* pRange = m_pDocument->GetRangeName();
    if( pRange )
    {
        const ScRangeData* pData = pRange->findByUpperName(ScGlobal::getCharClass().uppercase(aPos));
@@ -2509,8 +2509,8 @@ bool ScDocShell::DdeSetData( const OUString& rItem,
    // because the address item in a DDE entry is *not* normalized when saved
    // into ODF.
    ScRange aRange;
    bool bValid = ( (aRange.Parse(aPos, m_aDocument, formula::FormulaGrammar::CONV_OOO ) & ScRefFlags::VALID) ||
                    (aRange.aStart.Parse(aPos, m_aDocument, formula::FormulaGrammar::CONV_OOO) & ScRefFlags::VALID) );
    bool bValid = ( (aRange.Parse(aPos, *m_pDocument, formula::FormulaGrammar::CONV_OOO ) & ScRefFlags::VALID) ||
                    (aRange.aStart.Parse(aPos, *m_pDocument, formula::FormulaGrammar::CONV_OOO) & ScRefFlags::VALID) );

    ScServerObject* pObj = nullptr;            // NULL = error
    if ( bValid )
@@ -2705,8 +2705,8 @@ void ScDocShell::EnableSharedSettings( bool bEnable )

    if ( bEnable )
    {
        m_aDocument.EndChangeTracking();
        m_aDocument.StartChangeTracking();
        m_pDocument->EndChangeTracking();
        m_pDocument->StartChangeTracking();

        // hide accept or reject changes dialog
        sal_uInt16 nId = ScAcceptChgDlgWrapper::GetChildWindowId();
@@ -2723,12 +2723,12 @@ void ScDocShell::EnableSharedSettings( bool bEnable )
    }
    else
    {
        m_aDocument.EndChangeTracking();
        m_pDocument->EndChangeTracking();
    }

    ScChangeViewSettings aChangeViewSet;
    aChangeViewSet.SetShowChanges( false );
    m_aDocument.SetChangeViewSettings( aChangeViewSet );
    m_pDocument->SetChangeViewSettings( aChangeViewSet );
}

uno::Reference< frame::XModel > ScDocShell::LoadSharedDocument()
diff --git a/sc/source/ui/docshell/docsh5.cxx b/sc/source/ui/docshell/docsh5.cxx
index eeabf41..d1749fe 100644
--- a/sc/source/ui/docshell/docsh5.cxx
+++ b/sc/source/ui/docshell/docsh5.cxx
@@ -97,18 +97,18 @@ bool ScDocShell::IsEditable() const
    // import into read-only document is possible - must be extended if other filters use api
    // #i108547# MSOOXML filter uses "IsChangeReadOnlyEnabled" property

    return !IsReadOnly() || m_aDocument.IsImportingXML() || m_aDocument.IsChangeReadOnlyEnabled();
    return !IsReadOnly() || m_pDocument->IsImportingXML() || m_pDocument->IsChangeReadOnlyEnabled();
}

void ScDocShell::DBAreaDeleted( SCTAB nTab, SCCOL nX1, SCROW nY1, SCCOL nX2 )
{
    ScDocShellModificator aModificator( *this );
    // the auto-filter is in the first row of the area
    m_aDocument.RemoveFlagsTab( nX1, nY1, nX2, nY1, nTab, ScMF::Auto );
    m_pDocument->RemoveFlagsTab( nX1, nY1, nX2, nY1, nTab, ScMF::Auto );
    PostPaint( nX1, nY1, nTab, nX2, nY1, nTab, PaintPartFlags::Grid );
    // No SetDocumentModified, as the unnamed database range might have to be restored later.
    // The UNO hint is broadcast directly instead, to keep UNO objects in valid state.
    m_aDocument.BroadcastUno( SfxHint( SfxHintId::DataChanged ) );
    m_pDocument->BroadcastUno( SfxHint( SfxHintId::DataChanged ) );
}

ScDBData* ScDocShell::GetDBData( const ScRange& rMarked, ScGetDBMode eMode, ScGetDBSelection eSel )
@@ -124,8 +124,8 @@ ScDBData* ScDocShell::GetDBData( const ScRange& rMarked, ScGetDBMode eMode, ScGe
    SCROW nEndRow = rMarked.aEnd.Row();
    //  Not simply GetDBAtCursor: The continuous data range for "unnamed" (GetDataArea) may be
    //  located next to the cursor; so a named DB range needs to be searched for there as well.
    ScDBCollection* pColl = m_aDocument.GetDBCollection();
    ScDBData* pData = m_aDocument.GetDBAtArea( nTab, nStartCol, nStartRow, nEndCol, nEndRow );
    ScDBCollection* pColl = m_pDocument->GetDBCollection();
    ScDBData* pData = m_pDocument->GetDBAtArea( nTab, nStartCol, nStartRow, nEndCol, nEndRow );
    if (!pData)
        pData = pColl->GetDBNearCursor(nCol, nRow, nTab );

@@ -165,7 +165,7 @@ ScDBData* ScDocShell::GetDBData( const ScRange& rMarked, ScGetDBMode eMode, ScGe
                    nEndCol = nStartCol;
                    nEndRow = nStartRow;
                }
                m_aDocument.GetDataArea( nTab, nStartCol, nStartRow, nEndCol, nEndRow, false, bOnlyDown );
                m_pDocument->GetDataArea( nTab, nStartCol, nStartRow, nEndCol, nEndRow, false, bOnlyDown );
                if ( nOldCol1 != nStartCol || nOldCol2 != nEndCol || nOldRow1 != nStartRow )
                    bUseThis = false;               // doesn't fit at all
                else if ( nOldRow2 != nEndRow )
@@ -214,12 +214,12 @@ ScDBData* ScDocShell::GetDBData( const ScRange& rMarked, ScGetDBMode eMode, ScGe
                nEndCol = nStartCol;
                nEndRow = nStartRow;
            }
            m_aDocument.GetDataArea( nTab, nStartCol, nStartRow, nEndCol, nEndRow, false, bOnlyDown );
            m_pDocument->GetDataArea( nTab, nStartCol, nStartRow, nEndCol, nEndRow, false, bOnlyDown );
        }

        bool bHasHeader = m_aDocument.HasColHeader( nStartCol,nStartRow, nEndCol,nEndRow, nTab );
        bool bHasHeader = m_pDocument->HasColHeader( nStartCol,nStartRow, nEndCol,nEndRow, nTab );

        ScDBData* pNoNameData = m_aDocument.GetAnonymousDBData(nTab);
        ScDBData* pNoNameData = m_pDocument->GetAnonymousDBData(nTab);
        if ( eMode != SC_DB_IMPORT && pNoNameData)
        {
            // Do not reset AutoFilter range during temporary operations on
@@ -230,12 +230,12 @@ ScDBData* ScDocShell::GetDBData( const ScRange& rMarked, ScGetDBMode eMode, ScGe
            if (eMode != SC_DB_AUTOFILTER && pNoNameData->HasAutoFilter())
            {
                bSheetLocal = false;
                pNoNameData = m_aDocument.GetAnonymousDBData();
                pNoNameData = m_pDocument->GetAnonymousDBData();
                if (!pNoNameData)
                {
                    m_aDocument.SetAnonymousDBData( std::unique_ptr<ScDBData>(new ScDBData( STR_DB_LOCAL_NONAME,
                    m_pDocument->SetAnonymousDBData( std::unique_ptr<ScDBData>(new ScDBData( STR_DB_LOCAL_NONAME,
                            nTab, nStartCol, nStartRow, nEndCol, nEndRow, true, bHasHeader) ) );
                    pNoNameData = m_aDocument.GetAnonymousDBData();
                    pNoNameData = m_pDocument->GetAnonymousDBData();
                }
                // ScDocShell::CancelAutoDBRange() would restore the
                // sheet-local anonymous DBData from pOldAutoDBRange, unset so
@@ -290,7 +290,7 @@ ScDBData* ScDocShell::GetDBData( const ScRange& rMarked, ScGetDBMode eMode, ScGe

            if (eMode==SC_DB_IMPORT)
            {
                m_aDocument.PreprocessDBDataUpdate();
                m_pDocument->PreprocessDBDataUpdate();
                pUndoColl.reset( new ScDBCollection( *pColl ) );   // Undo for import range

                OUString aImport = ScResId( STR_DBNAME_IMPORT );
@@ -316,12 +316,12 @@ ScDBData* ScDocShell::GetDBData( const ScRange& rMarked, ScGetDBMode eMode, ScGe
                pNoNameData = new ScDBData(STR_DB_LOCAL_NONAME, nTab,
                                nStartCol,nStartRow, nEndCol,nEndRow,
                                true, bHasHeader );
                m_aDocument.SetAnonymousDBData(nTab, std::unique_ptr<ScDBData>(pNoNameData));
                m_pDocument->SetAnonymousDBData(nTab, std::unique_ptr<ScDBData>(pNoNameData));
            }

            if ( pUndoColl )
            {
                m_aDocument.CompileHybridFormula();
                m_pDocument->CompileHybridFormula();

                GetUndoManager()->AddUndoAction( std::make_unique<ScUndoDBData>( this,
                        std::move(pUndoColl),
@@ -342,7 +342,7 @@ ScDBData* ScDocShell::GetDBData( const ScRange& rMarked, ScGetDBMode eMode, ScGe

ScDBData* ScDocShell::GetAnonymousDBData(const ScRange& rRange)
{
    ScDBCollection* pColl = m_aDocument.GetDBCollection();
    ScDBCollection* pColl = m_pDocument->GetDBCollection();
    if (!pColl)
        return nullptr;

@@ -352,7 +352,7 @@ ScDBData* ScDocShell::GetAnonymousDBData(const ScRange& rRange)

    if (!pData->HasHeader())
    {
        bool bHasHeader = m_aDocument.HasColHeader(
        bool bHasHeader = m_pDocument->HasColHeader(
                rRange.aStart.Col(), rRange.aStart.Row(), rRange.aEnd.Col(), rRange.aEnd.Row(), rRange.aStart.Tab());
        pData->SetHeader(bHasHeader);
    }
@@ -373,7 +373,7 @@ void ScDocShell::CancelAutoDBRange()
        return;

    SCTAB nTab = GetCurTab();
    ScDBData* pDBData = m_aDocument.GetAnonymousDBData(nTab);
    ScDBData* pDBData = m_pDocument->GetAnonymousDBData(nTab);
    if ( pDBData )
    {
        SCCOL nRangeX1;
@@ -390,7 +390,7 @@ void ScDocShell::CancelAutoDBRange()
        {
            // restore AutoFilter buttons
            m_pOldAutoDBRange->GetArea( nRangeTab, nRangeX1, nRangeY1, nRangeX2, nRangeY2 );
            m_aDocument.ApplyFlagsTab( nRangeX1, nRangeY1, nRangeX2, nRangeY1, nRangeTab, ScMF::Auto );
            m_pDocument->ApplyFlagsTab( nRangeX1, nRangeY1, nRangeX2, nRangeY1, nRangeTab, ScMF::Auto );
            PostPaint( nRangeX1, nRangeY1, nRangeTab, nRangeX2, nRangeY1, nRangeTab, PaintPartFlags::Grid );
        }
    }
@@ -405,15 +405,15 @@ bool ScDocShell::AdjustRowHeight( SCROW nStartRow, SCROW nEndRow, SCTAB nTab )
{
    ScSizeDeviceProvider aProv(this);
    Fraction aZoom(1,1);
    sc::RowHeightContext aCxt(m_aDocument.MaxRow(), aProv.GetPPTX(), aProv.GetPPTY(), aZoom, aZoom, aProv.GetDevice());
    bool bChange = m_aDocument.SetOptimalHeight(aCxt, nStartRow,nEndRow, nTab, true);
    sc::RowHeightContext aCxt(m_pDocument->MaxRow(), aProv.GetPPTX(), aProv.GetPPTY(), aZoom, aZoom, aProv.GetDevice());
    bool bChange = m_pDocument->SetOptimalHeight(aCxt, nStartRow,nEndRow, nTab, true);

    if (bChange)
    {
        // tdf#76183: recalculate objects' positions
        m_aDocument.SetDrawPageSize(nTab);
        m_pDocument->SetDrawPageSize(nTab);

        PostPaint( 0,nStartRow,nTab, m_aDocument.MaxCol(),m_aDocument.MaxRow(),nTab, PaintPartFlags::Grid|PaintPartFlags::Left );
        PostPaint( 0,nStartRow,nTab, m_pDocument->MaxCol(),m_pDocument->MaxRow(),nTab, PaintPartFlags::Grid|PaintPartFlags::Left );
    }

    return bChange;
@@ -425,25 +425,25 @@ void ScDocShell::UpdateAllRowHeights( const ScMarkData* pTabMark )

    ScSizeDeviceProvider aProv(this);
    Fraction aZoom(1,1);
    sc::RowHeightContext aCxt(m_aDocument.MaxRow(), aProv.GetPPTX(), aProv.GetPPTY(), aZoom, aZoom, aProv.GetDevice());
    m_aDocument.UpdateAllRowHeights(aCxt, pTabMark);
    sc::RowHeightContext aCxt(m_pDocument->MaxRow(), aProv.GetPPTX(), aProv.GetPPTY(), aZoom, aZoom, aProv.GetDevice());
    m_pDocument->UpdateAllRowHeights(aCxt, pTabMark);
}

void ScDocShell::UpdatePendingRowHeights( SCTAB nUpdateTab, bool bBefore )
{
    bool bIsUndoEnabled = m_aDocument.IsUndoEnabled();
    m_aDocument.EnableUndo( false );
    m_aDocument.LockStreamValid( true );      // ignore draw page size (but not formula results)
    bool bIsUndoEnabled = m_pDocument->IsUndoEnabled();
    m_pDocument->EnableUndo( false );
    m_pDocument->LockStreamValid( true );      // ignore draw page size (but not formula results)
    if ( bBefore )          // check all sheets up to nUpdateTab
    {
        SCTAB nTabCount = m_aDocument.GetTableCount();
        SCTAB nTabCount = m_pDocument->GetTableCount();
        if ( nUpdateTab >= nTabCount )
            nUpdateTab = nTabCount-1;     // nUpdateTab is inclusive

        ScMarkData aUpdateSheets(m_aDocument.GetSheetLimits());
        ScMarkData aUpdateSheets(m_pDocument->GetSheetLimits());
        SCTAB nTab;
        for (nTab=0; nTab<=nUpdateTab; ++nTab)
            if ( m_aDocument.IsPendingRowHeights( nTab ) )
            if ( m_pDocument->IsPendingRowHeights( nTab ) )
                aUpdateSheets.SelectTable( nTab, true );

        if (aUpdateSheets.GetSelectCount())
@@ -452,26 +452,26 @@ void ScDocShell::UpdatePendingRowHeights( SCTAB nUpdateTab, bool bBefore )
        for (nTab=0; nTab<=nUpdateTab; ++nTab)
            if ( aUpdateSheets.GetTableSelect( nTab ) )
            {
                m_aDocument.UpdatePageBreaks( nTab );
                m_aDocument.SetPendingRowHeights( nTab, false );
                m_pDocument->UpdatePageBreaks( nTab );
                m_pDocument->SetPendingRowHeights( nTab, false );
            }
    }
    else                    // only nUpdateTab
    {
        if ( m_aDocument.IsPendingRowHeights( nUpdateTab ) )
        if ( m_pDocument->IsPendingRowHeights( nUpdateTab ) )
        {
            AdjustRowHeight( 0, m_aDocument.MaxRow(), nUpdateTab );
            m_aDocument.UpdatePageBreaks( nUpdateTab );
            m_aDocument.SetPendingRowHeights( nUpdateTab, false );
            AdjustRowHeight( 0, m_pDocument->MaxRow(), nUpdateTab );
            m_pDocument->UpdatePageBreaks( nUpdateTab );
            m_pDocument->SetPendingRowHeights( nUpdateTab, false );
        }
    }
    m_aDocument.LockStreamValid( false );
    m_aDocument.EnableUndo( bIsUndoEnabled );
    m_pDocument->LockStreamValid( false );
    m_pDocument->EnableUndo( bIsUndoEnabled );
}

void ScDocShell::RefreshPivotTables( const ScRange& rSource )
{
    ScDPCollection* pColl = m_aDocument.GetDPCollection();
    ScDPCollection* pColl = m_pDocument->GetDPCollection();
    if (!pColl)
        return;

@@ -533,7 +533,7 @@ void ScDocShell::DoConsolidate( const ScConsolidateParam& rParam, bool bRecord )
    ScDocShellModificator aModificator( *this );

    ScRange aOldDest;
    ScDBData* pDestData = m_aDocument.GetDBAtCursor( rParam.nCol, rParam.nRow, rParam.nTab, ScDBDataPortion::TOP_LEFT );
    ScDBData* pDestData = m_pDocument->GetDBAtCursor( rParam.nCol, rParam.nRow, rParam.nTab, ScDBDataPortion::TOP_LEFT );
    if (pDestData)
        pDestData->GetArea(aOldDest);

@@ -543,16 +543,16 @@ void ScDocShell::DoConsolidate( const ScConsolidateParam& rParam, bool bRecord )
        for (nPos=0; nPos<rParam.nDataAreaCount; nPos++)
        {
            ScArea const & rArea = rParam.pDataAreas[nPos];
            aData.AddFields( &m_aDocument, rArea.nTab, rArea.nColStart, rArea.nRowStart,
            aData.AddFields( m_pDocument.get(), rArea.nTab, rArea.nColStart, rArea.nRowStart,
                                                       rArea.nColEnd, rArea.nRowEnd );
        }
    aData.DoneFields();
    for (nPos=0; nPos<rParam.nDataAreaCount; nPos++)
    {
        ScArea const & rArea = rParam.pDataAreas[nPos];
        aData.AddData( &m_aDocument, rArea.nTab, rArea.nColStart, rArea.nRowStart,
        aData.AddData( m_pDocument.get(), rArea.nTab, rArea.nColStart, rArea.nRowStart,
                                                 rArea.nColEnd, rArea.nRowEnd );
        aData.AddName( lcl_GetAreaName(&m_aDocument, &rArea) );
        aData.AddName( lcl_GetAreaName(m_pDocument.get(), &rArea) );
    }

    aData.GetSize( nColSize, nRowSize );
@@ -568,32 +568,32 @@ void ScDocShell::DoConsolidate( const ScConsolidateParam& rParam, bool bRecord )

        if (rParam.bReferenceData)
        {
            SCTAB nTabCount = m_aDocument.GetTableCount();
            SCTAB nTabCount = m_pDocument->GetTableCount();
            SCROW nInsertCount = aData.GetInsertCount();

            // old outlines
            ScOutlineTable* pTable = m_aDocument.GetOutlineTable( nDestTab );
            ScOutlineTable* pTable = m_pDocument->GetOutlineTable( nDestTab );
            std::unique_ptr<ScOutlineTable> pUndoTab(pTable ? new ScOutlineTable( *pTable ) : nullptr);

            ScDocumentUniquePtr pUndoDoc(new ScDocument( SCDOCMODE_UNDO ));
            pUndoDoc->InitUndo( m_aDocument, 0, nTabCount-1, false, true );
            pUndoDoc->InitUndo( *m_pDocument, 0, nTabCount-1, false, true );

            // row state
            m_aDocument.CopyToDocument(0, 0, nDestTab, m_aDocument.MaxCol(), m_aDocument.MaxRow(), nDestTab,
            m_pDocument->CopyToDocument(0, 0, nDestTab, m_pDocument->MaxCol(), m_pDocument->MaxRow(), nDestTab,
                                     InsertDeleteFlags::NONE, false, *pUndoDoc);

            // all formulas
            m_aDocument.CopyToDocument(0, 0, 0, m_aDocument.MaxCol(), m_aDocument.MaxRow(), nTabCount-1,
            m_pDocument->CopyToDocument(0, 0, 0, m_pDocument->MaxCol(), m_pDocument->MaxRow(), nTabCount-1,
                                     InsertDeleteFlags::FORMULA, false, *pUndoDoc);

            // complete output rows
            m_aDocument.CopyToDocument(0, aDestArea.nRowStart, nDestTab,
                                     m_aDocument.MaxCol(),aDestArea.nRowEnd, nDestTab,
            m_pDocument->CopyToDocument(0, aDestArea.nRowStart, nDestTab,
                                     m_pDocument->MaxCol(),aDestArea.nRowEnd, nDestTab,
                                     InsertDeleteFlags::ALL, false, *pUndoDoc);

            // old output range
            if (pDestData)
                m_aDocument.CopyToDocument(aOldDest, InsertDeleteFlags::ALL, false, *pUndoDoc);
                m_pDocument->CopyToDocument(aOldDest, InsertDeleteFlags::ALL, false, *pUndoDoc);

            GetUndoManager()->AddUndoAction(
                    std::make_unique<ScUndoConsolidate>( this, aDestArea, rParam, std::move(pUndoDoc),
@@ -602,15 +602,15 @@ void ScDocShell::DoConsolidate( const ScConsolidateParam& rParam, bool bRecord )
        else
        {
            ScDocumentUniquePtr pUndoDoc(new ScDocument( SCDOCMODE_UNDO ));
            pUndoDoc->InitUndo( m_aDocument, aDestArea.nTab, aDestArea.nTab );
            pUndoDoc->InitUndo( *m_pDocument, aDestArea.nTab, aDestArea.nTab );

            m_aDocument.CopyToDocument(aDestArea.nColStart, aDestArea.nRowStart, aDestArea.nTab,
            m_pDocument->CopyToDocument(aDestArea.nColStart, aDestArea.nRowStart, aDestArea.nTab,
                                     aDestArea.nColEnd, aDestArea.nRowEnd, aDestArea.nTab,
                                     InsertDeleteFlags::ALL, false, *pUndoDoc);

            // old output range
            if (pDestData)
                m_aDocument.CopyToDocument(aOldDest, InsertDeleteFlags::ALL, false, *pUndoDoc);
                m_pDocument->CopyToDocument(aOldDest, InsertDeleteFlags::ALL, false, *pUndoDoc);

            GetUndoManager()->AddUndoAction(
                    std::make_unique<ScUndoConsolidate>( this, aDestArea, rParam, std::move(pUndoDoc),
@@ -620,13 +620,13 @@ void ScDocShell::DoConsolidate( const ScConsolidateParam& rParam, bool bRecord )

    if (pDestData)                                      // delete / adjust destination range
    {
        m_aDocument.DeleteAreaTab(aOldDest, InsertDeleteFlags::CONTENTS);
        m_pDocument->DeleteAreaTab(aOldDest, InsertDeleteFlags::CONTENTS);
        pDestData->SetArea( rParam.nTab, rParam.nCol, rParam.nRow,
                            rParam.nCol + nColSize - 1, rParam.nRow + nRowSize - 1 );
        pDestData->SetHeader( rParam.bByRow );
    }

    aData.OutputToDocument( m_aDocument, rParam.nCol, rParam.nRow, rParam.nTab );
    aData.OutputToDocument( *m_pDocument, rParam.nCol, rParam.nRow, rParam.nTab );

    SCCOL nPaintStartCol = rParam.nCol;
    SCROW nPaintStartRow = rParam.nRow;
@@ -640,8 +640,8 @@ void ScDocShell::DoConsolidate( const ScConsolidateParam& rParam, bool bRecord )
    if (rParam.bReferenceData)
    {
        nPaintStartCol = 0;
        nPaintEndCol = m_aDocument.MaxCol();
        nPaintEndRow = m_aDocument.MaxRow();
        nPaintEndCol = m_pDocument->MaxCol();
        nPaintEndRow = m_pDocument->MaxRow();
        nPaintFlags |= PaintPartFlags::Left | PaintPartFlags::Size;
    }
    if (pDestData)
@@ -658,29 +658,29 @@ void ScDocShell::DoConsolidate( const ScConsolidateParam& rParam, bool bRecord )

void ScDocShell::UseScenario( SCTAB nTab, const OUString& rName, bool bRecord )
{
    if (!m_aDocument.IsScenario(nTab))
    if (!m_pDocument->IsScenario(nTab))
    {
        SCTAB   nTabCount = m_aDocument.GetTableCount();
        SCTAB   nTabCount = m_pDocument->GetTableCount();
        SCTAB   nSrcTab = SCTAB_MAX;
        SCTAB   nEndTab = nTab;
        OUString aCompare;
        while ( nEndTab+1 < nTabCount && m_aDocument.IsScenario(nEndTab+1) )
        while ( nEndTab+1 < nTabCount && m_pDocument->IsScenario(nEndTab+1) )
        {
            ++nEndTab;
            if (nSrcTab > MAXTAB)           // still searching for the scenario?
            {
                m_aDocument.GetName( nEndTab, aCompare );
                m_pDocument->GetName( nEndTab, aCompare );
                if (aCompare == rName)
                    nSrcTab = nEndTab;      // found
            }
        }
        if (ValidTab(nSrcTab))
        {
            if ( m_aDocument.TestCopyScenario( nSrcTab, nTab ) )          // test cell protection
            if ( m_pDocument->TestCopyScenario( nSrcTab, nTab ) )          // test cell protection
            {
                ScDocShellModificator aModificator( *this );
                ScMarkData aScenMark(m_aDocument.GetSheetLimits());
                m_aDocument.MarkScenario( nSrcTab, nTab, aScenMark );
                ScMarkData aScenMark(m_pDocument->GetSheetLimits());
                m_pDocument->MarkScenario( nSrcTab, nTab, aScenMark );
                const ScRange& aMultiRange = aScenMark.GetMultiMarkArea();
                SCCOL nStartCol = aMultiRange.aStart.Col();
                SCROW nStartRow = aMultiRange.aStart.Row();
@@ -690,9 +690,9 @@ void ScDocShell::UseScenario( SCTAB nTab, const OUString& rName, bool bRecord )
                if (bRecord)
                {
                    ScDocumentUniquePtr pUndoDoc(new ScDocument( SCDOCMODE_UNDO ));
                    pUndoDoc->InitUndo( m_aDocument, nTab,nEndTab );             // also all scenarios
                    pUndoDoc->InitUndo( *m_pDocument, nTab,nEndTab );             // also all scenarios
                    //  shown table:
                    m_aDocument.CopyToDocument(nStartCol, nStartRow, nTab,
                    m_pDocument->CopyToDocument(nStartCol, nStartRow, nTab,
                                             nEndCol, nEndRow, nTab, InsertDeleteFlags::ALL,
                                             true, *pUndoDoc, &aScenMark);
                    //  scenarios
@@ -702,13 +702,13 @@ void ScDocShell::UseScenario( SCTAB nTab, const OUString& rName, bool bRecord )
                        OUString aComment;
                        Color  aColor;
                        ScScenarioFlags nScenFlags;
                        m_aDocument.GetScenarioData( i, aComment, aColor, nScenFlags );
                        m_pDocument->GetScenarioData( i, aComment, aColor, nScenFlags );
                        pUndoDoc->SetScenarioData( i, aComment, aColor, nScenFlags );
                        bool bActive = m_aDocument.IsActiveScenario( i );
                        bool bActive = m_pDocument->IsActiveScenario( i );
                        pUndoDoc->SetActiveScenario( i, bActive );
                        //  At copy-back scenarios also contents
                        if ( nScenFlags & ScScenarioFlags::TwoWay )
                            m_aDocument.CopyToDocument(0, 0, i, m_aDocument.MaxCol(), m_aDocument.MaxRow(), i,
                            m_pDocument->CopyToDocument(0, 0, i, m_pDocument->MaxCol(), m_pDocument->MaxRow(), i,
                                                     InsertDeleteFlags::ALL, false, *pUndoDoc );
                    }

@@ -718,14 +718,14 @@ void ScDocShell::UseScenario( SCTAB nTab, const OUString& rName, bool bRecord )
                                        std::move(pUndoDoc), rName ) );
                }

                m_aDocument.CopyScenario( nSrcTab, nTab );
                m_pDocument->CopyScenario( nSrcTab, nTab );

                sc::SetFormulaDirtyContext aCxt;
                m_aDocument.SetAllFormulasDirty(aCxt);
                m_pDocument->SetAllFormulasDirty(aCxt);

                //  paint all, because the active scenario may be modified in other ranges;
                //! only if there are visible frames?
                PostPaint( 0,0,nTab, m_aDocument.MaxCol(),m_aDocument.MaxRow(),nTab, PaintPartFlags::Grid );
                PostPaint( 0,0,nTab, m_pDocument->MaxCol(),m_pDocument->MaxRow(),nTab, PaintPartFlags::Grid );
                aModificator.SetDocumentModified();
            }
            else
@@ -755,11 +755,11 @@ void ScDocShell::ModifyScenario( SCTAB nTab, const OUString& rName, const OUStri
{
    //  Undo
    OUString aOldName;
    m_aDocument.GetName( nTab, aOldName );
    m_pDocument->GetName( nTab, aOldName );
    OUString aOldComment;
    Color aOldColor;
    ScScenarioFlags nOldFlags;
    m_aDocument.GetScenarioData( nTab, aOldComment, aOldColor, nOldFlags );
    m_pDocument->GetScenarioData( nTab, aOldComment, aOldColor, nOldFlags );
    GetUndoManager()->AddUndoAction(
        std::make_unique<ScUndoScenarioFlags>(this, nTab,
                aOldName, rName, aOldComment, rComment,
@@ -767,8 +767,8 @@ void ScDocShell::ModifyScenario( SCTAB nTab, const OUString& rName, const OUStri

    //  execute
    ScDocShellModificator aModificator( *this );
    m_aDocument.RenameTab( nTab, rName );
    m_aDocument.SetScenarioData( nTab, rComment, rColor, nFlags );
    m_pDocument->RenameTab( nTab, rName );
    m_pDocument->SetScenarioData( nTab, rComment, rColor, nFlags );
    PostPaintGridAll();
    aModificator.SetDocumentModified();

@@ -788,7 +788,7 @@ SCTAB ScDocShell::MakeScenario( SCTAB nTab, const OUString& rName, const OUStrin
    if (rMark.IsMultiMarked())
    {
        SCTAB nNewTab = nTab + 1;
        while (m_aDocument.IsScenario(nNewTab))
        while (m_pDocument->IsScenario(nNewTab))
            ++nNewTab;

        bool bCopyAll = ( (nFlags & ScScenarioFlags::CopyAll) != ScScenarioFlags::NONE );
@@ -799,9 +799,9 @@ SCTAB ScDocShell::MakeScenario( SCTAB nTab, const OUString& rName, const OUStrin
        ScDocShellModificator aModificator( *this );

        if (bRecord)
            m_aDocument.BeginDrawUndo();      // drawing layer must do its own undo actions
            m_pDocument->BeginDrawUndo();      // drawing layer must do its own undo actions

        if (m_aDocument.CopyTab( nTab, nNewTab, pCopyMark ))
        if (m_pDocument->CopyTab( nTab, nNewTab, pCopyMark ))
        {
            if (bRecord)
            {
@@ -810,32 +810,32 @@ SCTAB ScDocShell::MakeScenario( SCTAB nTab, const OUString& rName, const OUStrin
                                                rName, rComment, rColor, nFlags, rMark ));
            }

            m_aDocument.RenameTab( nNewTab, rName);
            m_aDocument.SetScenario( nNewTab, true );
            m_aDocument.SetScenarioData( nNewTab, rComment, rColor, nFlags );
            m_pDocument->RenameTab( nNewTab, rName);
            m_pDocument->SetScenario( nNewTab, true );
            m_pDocument->SetScenarioData( nNewTab, rComment, rColor, nFlags );

            ScMarkData aDestMark = rMark;
            aDestMark.SelectOneTable( nNewTab );

            //!     test for filter / buttons / merging

            ScPatternAttr aProtPattern( m_aDocument.GetPool() );
            ScPatternAttr aProtPattern( m_pDocument->GetPool() );
            aProtPattern.GetItemSet().Put( ScProtectionAttr( true ) );
            m_aDocument.ApplyPatternAreaTab( 0,0, m_aDocument.MaxCol(),m_aDocument.MaxRow(), nNewTab, aProtPattern );
            m_pDocument->ApplyPatternAreaTab( 0,0, m_pDocument->MaxCol(),m_pDocument->MaxRow(), nNewTab, aProtPattern );

            ScPatternAttr aPattern( m_aDocument.GetPool() );
            ScPatternAttr aPattern( m_pDocument->GetPool() );
            aPattern.GetItemSet().Put( ScMergeFlagAttr( ScMF::Scenario ) );
            aPattern.GetItemSet().Put( ScProtectionAttr( true ) );
            m_aDocument.ApplySelectionPattern( aPattern, aDestMark );
            m_pDocument->ApplySelectionPattern( aPattern, aDestMark );

            if (!bCopyAll)
                m_aDocument.SetVisible( nNewTab, false );
                m_pDocument->SetVisible( nNewTab, false );

            //  this is the active scenario, then
            m_aDocument.CopyScenario( nNewTab, nTab, true );  // sal_True - don't copy anything from scenario
            m_pDocument->CopyScenario( nNewTab, nTab, true );  // sal_True - don't copy anything from scenario

            if (nFlags & ScScenarioFlags::ShowFrame)
                PostPaint( 0,0,nTab, m_aDocument.MaxCol(),m_aDocument.MaxRow(),nTab, PaintPartFlags::Grid );  // paint frames
                PostPaint( 0,0,nTab, m_pDocument->MaxCol(),m_pDocument->MaxRow(),nTab, PaintPartFlags::Grid );  // paint frames
            PostPaintExtras();                                          // table tab
            aModificator.SetDocumentModified();

@@ -858,16 +858,16 @@ sal_uLong ScDocShell::TransferTab( ScDocShell& rSrcDocShell, SCTAB nSrcPos,

    // set the transferred area to the copyparam to make adjusting formulas possible
    ScClipParam aParam;
    ScRange aRange(0, 0, nSrcPos, m_aDocument.MaxCol(), m_aDocument.MaxRow(), nSrcPos);
    ScRange aRange(0, 0, nSrcPos, m_pDocument->MaxCol(), m_pDocument->MaxRow(), nSrcPos);
    aParam.maRanges.push_back(aRange);
    rSrcDoc.SetClipParam(aParam);

    sal_uLong nErrVal =  m_aDocument.TransferTab( rSrcDoc, nSrcPos, nDestPos,
    sal_uLong nErrVal =  m_pDocument->TransferTab( rSrcDoc, nSrcPos, nDestPos,
                    bInsertNew );       // no insert

    // TransferTab doesn't copy drawing objects with bInsertNew=FALSE
    if ( nErrVal > 0 && !bInsertNew)
        m_aDocument.TransferDrawPage( rSrcDoc, nSrcPos, nDestPos );
        m_pDocument->TransferDrawPage( rSrcDoc, nSrcPos, nDestPos );

    if(nErrVal>0 && rSrcDoc.IsScenario( nSrcPos ))
    {
@@ -876,18 +876,18 @@ sal_uLong ScDocShell::TransferTab( ScDocShell& rSrcDocShell, SCTAB nSrcPos,
        ScScenarioFlags nFlags;

        rSrcDoc.GetScenarioData( nSrcPos, aComment,aColor, nFlags);
        m_aDocument.SetScenario(nDestPos,true);
        m_aDocument.SetScenarioData(nDestPos,aComment,aColor,nFlags);
        m_pDocument->SetScenario(nDestPos,true);
        m_pDocument->SetScenarioData(nDestPos,aComment,aColor,nFlags);
        bool bActive = rSrcDoc.IsActiveScenario(nSrcPos);
        m_aDocument.SetActiveScenario(nDestPos, bActive );
        m_pDocument->SetActiveScenario(nDestPos, bActive );

        bool bVisible = rSrcDoc.IsVisible(nSrcPos);
        m_aDocument.SetVisible(nDestPos,bVisible );
        m_pDocument->SetVisible(nDestPos,bVisible );

    }

    if ( nErrVal > 0 && rSrcDoc.IsTabProtected( nSrcPos ) )
        m_aDocument.SetTabProtection(nDestPos, rSrcDoc.GetTabProtection(nSrcPos));
        m_pDocument->SetTabProtection(nDestPos, rSrcDoc.GetTabProtection(nSrcPos));
    if ( bNotifyAndPaint )
    {
            Broadcast( ScTablesHint( SC_TAB_INSERTED, nDestPos ) );
@@ -903,17 +903,17 @@ bool ScDocShell::MoveTable( SCTAB nSrcTab, SCTAB nDestTab, bool bCopy, bool bRec

    // #i92477# be consistent with ScDocFunc::InsertTable: any index past the last sheet means "append"
    // #i101139# nDestTab must be the target position, not APPEND (for CopyTabProtection etc.)
    if ( nDestTab >= m_aDocument.GetTableCount() )
        nDestTab = m_aDocument.GetTableCount();
    if ( nDestTab >= m_pDocument->GetTableCount() )
        nDestTab = m_pDocument->GetTableCount();

    if (bCopy)
    {
        if (bRecord)
            m_aDocument.BeginDrawUndo();          // drawing layer must do its own undo actions
            m_pDocument->BeginDrawUndo();          // drawing layer must do its own undo actions

        OUString sSrcCodeName;
        m_aDocument.GetCodeName( nSrcTab, sSrcCodeName );
        if (!m_aDocument.CopyTab( nSrcTab, nDestTab ))
        m_pDocument->GetCodeName( nSrcTab, sSrcCodeName );
        if (!m_pDocument->CopyTab( nSrcTab, nDestTab ))
        {
            //! EndDrawUndo?
            return false;
@@ -924,8 +924,8 @@ bool ScDocShell::MoveTable( SCTAB nSrcTab, SCTAB nDestTab, bool bCopy, bool bRec
            if ( nDestTab <= nSrcTab )
                ++nAdjSource;               // new position of source table after CopyTab

            if ( m_aDocument.IsTabProtected( nAdjSource ) )
                m_aDocument.CopyTabProtection(nAdjSource, nDestTab);
            if ( m_pDocument->IsTabProtected( nAdjSource ) )
                m_pDocument->CopyTabProtection(nAdjSource, nDestTab);

            if (bRecord)
            {
@@ -935,7 +935,7 @@ bool ScDocShell::MoveTable( SCTAB nSrcTab, SCTAB nDestTab, bool bCopy, bool bRec
                        std::make_unique<ScUndoCopyTab>(this, std::move(pSrcList), std::move(pDestList)));
            }

            bool bVbaEnabled = m_aDocument.IsInVBAMode();
            bool bVbaEnabled = m_pDocument->IsInVBAMode();
            if ( bVbaEnabled )
            {
                OUString aLibName( "Standard" );
@@ -949,7 +949,7 @@ bool ScDocShell::MoveTable( SCTAB nSrcTab, SCTAB nDestTab, bool bCopy, bool bRec

                SCTAB nTabToUse = nDestTab;
                if ( nDestTab == SC_TAB_APPEND )
                    nTabToUse = m_aDocument.GetMaxTableNumber() - 1;
                    nTabToUse = m_pDocument->GetMaxTableNumber() - 1;
                OUString sSource;
                try
                {
@@ -967,14 +967,14 @@ bool ScDocShell::MoveTable( SCTAB nSrcTab, SCTAB nDestTab, bool bCopy, bool bRec
                catch ( const css::uno::Exception& )
                {
                }
                VBA_InsertModule( m_aDocument, nTabToUse, sSource );
                VBA_InsertModule( *m_pDocument, nTabToUse, sSource );
            }
        }
        Broadcast( ScTablesHint( SC_TAB_COPIED, nSrcTab, nDestTab ) );
    }
    else
    {
        if ( m_aDocument.GetChangeTrack() )
        if ( m_pDocument->GetChangeTrack() )
            return false;

        if ( nSrcTab<nDestTab && nDestTab!=SC_TAB_APPEND )
@@ -987,8 +987,8 @@ bool ScDocShell::MoveTable( SCTAB nSrcTab, SCTAB nDestTab, bool bCopy, bool bRec
        }

        std::optional<ScProgress> pProgress(std::in_place, this, ScResId(STR_UNDO_MOVE_TAB),
                                                m_aDocument.GetCodeCount(), true);
        bool bDone = m_aDocument.MoveTab( nSrcTab, nDestTab, &*pProgress );
                                                m_pDocument->GetCodeCount(), true);
        bool bDone = m_pDocument->MoveTab( nSrcTab, nDestTab, &*pProgress );
        pProgress.reset();
        if (!bDone)
        {
diff --git a/sc/source/ui/docshell/docsh6.cxx b/sc/source/ui/docshell/docsh6.cxx
index ce4d03f..738c8511 100644
--- a/sc/source/ui/docshell/docsh6.cxx
+++ b/sc/source/ui/docshell/docsh6.cxx
@@ -72,12 +72,12 @@ static void lcl_SetTopRight( tools::Rectangle& rRect, const Point& rPos )

void ScDocShell::SetVisAreaOrSize( const tools::Rectangle& rVisArea )
{
    bool bNegativePage = m_aDocument.IsNegativePage( m_aDocument.GetVisibleTab() );
    bool bNegativePage = m_pDocument->IsNegativePage( m_pDocument->GetVisibleTab() );

    tools::Rectangle aArea = rVisArea;
    // when loading, don't check for negative values, because the sheet orientation
    // might be set later
    if ( !m_aDocument.IsImportingXML() )
    if ( !m_pDocument->IsImportingXML() )
    {
        if ( ( bNegativePage ? (aArea.Right() > 0) : (aArea.Left() < 0) ) || aArea.Top() < 0 )
        {
@@ -103,7 +103,7 @@ void ScDocShell::SetVisAreaOrSize( const tools::Rectangle& rVisArea )

    //  when loading an ole object, the VisArea is set from the document's
    //  view settings and must be used as-is (document content may not be complete yet).
    if ( !m_aDocument.IsImportingXML() )
    if ( !m_pDocument->IsImportingXML() )
        SnapVisArea( aArea );

    //TODO/LATER: it's unclear which IPEnv is used here
@@ -129,16 +129,16 @@ void ScDocShell::SetVisAreaOrSize( const tools::Rectangle& rVisArea )
        }
    }

    if (!m_aDocument.IsEmbedded())
    if (!m_pDocument->IsEmbedded())
        return;

    ScRange aOld;
    m_aDocument.GetEmbedded( aOld);
    m_aDocument.SetEmbedded( m_aDocument.GetVisibleTab(), aArea );
    m_pDocument->GetEmbedded( aOld);
    m_pDocument->SetEmbedded( m_pDocument->GetVisibleTab(), aArea );
    ScRange aNew;
    m_aDocument.GetEmbedded( aNew);
    m_pDocument->GetEmbedded( aNew);
    if (aOld != aNew)
        PostPaint(0,0,0,m_aDocument.MaxCol(),m_aDocument.MaxRow(),MAXTAB,PaintPartFlags::Grid);
        PostPaint(0,0,0,m_pDocument->MaxCol(),m_pDocument->MaxRow(),MAXTAB,PaintPartFlags::Grid);

    //TODO/LATER: currently not implemented
    //ViewChanged( ASPECT_CONTENT );          // show in the container as well
@@ -160,23 +160,23 @@ void ScDocShell::UpdateOle(const ScViewData& rViewData, bool bSnapSize)
    tools::Rectangle aOldArea = SfxObjectShell::GetVisArea();
    tools::Rectangle aNewArea = aOldArea;

    bool bEmbedded = m_aDocument.IsEmbedded();
    bool bEmbedded = m_pDocument->IsEmbedded();
    if (bEmbedded)
        aNewArea = m_aDocument.GetEmbeddedRect();
        aNewArea = m_pDocument->GetEmbeddedRect();
    else
    {
        SCTAB nTab = rViewData.GetTabNo();
        if ( nTab != m_aDocument.GetVisibleTab() )
            m_aDocument.SetVisibleTab( nTab );
        if ( nTab != m_pDocument->GetVisibleTab() )
            m_pDocument->SetVisibleTab( nTab );

        bool bNegativePage = m_aDocument.IsNegativePage( nTab );
        bool bNegativePage = m_pDocument->IsNegativePage( nTab );
        SCCOL nX = rViewData.GetPosX(SC_SPLIT_LEFT);
        if ( nX != m_aDocument.GetPosLeft() )
            m_aDocument.SetPosLeft( nX );
        if ( nX != m_pDocument->GetPosLeft() )
            m_pDocument->SetPosLeft( nX );
        SCROW nY = rViewData.GetPosY(SC_SPLIT_BOTTOM);
        if ( nY != m_aDocument.GetPosTop() )
            m_aDocument.SetPosTop( nY );
        tools::Rectangle aMMRect = m_aDocument.GetMMRect( nX,nY, nX,nY, nTab );
        if ( nY != m_pDocument->GetPosTop() )
            m_pDocument->SetPosTop( nY );
        tools::Rectangle aMMRect = m_pDocument->GetMMRect( nX,nY, nX,nY, nTab );
        if (bNegativePage)
            lcl_SetTopRight( aNewArea, aMMRect.TopRight() );
        else
@@ -193,7 +193,7 @@ void ScDocShell::UpdateOle(const ScViewData& rViewData, bool bSnapSize)

SfxStyleSheetBasePool* ScDocShell::GetStyleSheetPool()
{
    return static_cast<SfxStyleSheetBasePool*>(m_aDocument.GetStyleSheetPool());
    return static_cast<SfxStyleSheetBasePool*>(m_pDocument->GetStyleSheetPool());
}

//  After loading styles from another document (LoadStyles, Insert), the SetItems
@@ -228,18 +228,18 @@ static void lcl_AdjustPool( SfxStyleSheetBasePool* pStylePool )

void ScDocShell::LoadStyles( SfxObjectShell &rSource )
{
    m_aDocument.StylesToNames();
    m_pDocument->StylesToNames();

    SfxObjectShell::LoadStyles(rSource);
    lcl_AdjustPool( GetStyleSheetPool() );      // adjust SetItems

    m_aDocument.UpdStlShtPtrsFrmNms();
    m_pDocument->UpdStlShtPtrsFrmNms();

    UpdateAllRowHeights();

        //  Paint

    PostPaint( 0,0,0, m_aDocument.MaxCol(),m_aDocument.MaxRow(),MAXTAB, PaintPartFlags::Grid | PaintPartFlags::Left );
    PostPaint( 0,0,0, m_pDocument->MaxCol(),m_pDocument->MaxRow(),MAXTAB, PaintPartFlags::Grid | PaintPartFlags::Left );
}

void ScDocShell::LoadStylesArgs( ScDocShell& rSource, bool bReplace, bool bCellStyles, bool bPageStyles )
@@ -250,7 +250,7 @@ void ScDocShell::LoadStylesArgs( ScDocShell& rSource, bool bReplace, bool bCellS
        return;

    ScStyleSheetPool* pSourcePool = rSource.GetDocument().GetStyleSheetPool();
    ScStyleSheetPool* pDestPool = m_aDocument.GetStyleSheetPool();
    ScStyleSheetPool* pDestPool = m_pDocument->GetStyleSheetPool();

    SfxStyleFamily eFamily = bCellStyles ?
            ( bPageStyles ? SfxStyleFamily::All : SfxStyleFamily::Para ) :
@@ -303,12 +303,12 @@ void ScDocShell::LoadStylesArgs( ScDocShell& rSource, bool bReplace, bool bCellS

    lcl_AdjustPool( GetStyleSheetPool() );      // adjust SetItems
    UpdateAllRowHeights();
    PostPaint( 0,0,0, m_aDocument.MaxCol(),m_aDocument.MaxRow(),MAXTAB, PaintPartFlags::Grid | PaintPartFlags::Left );      // Paint
    PostPaint( 0,0,0, m_pDocument->MaxCol(),m_pDocument->MaxRow(),MAXTAB, PaintPartFlags::Grid | PaintPartFlags::Left );      // Paint
}

void ScDocShell::ReconnectDdeLink(SfxObjectShell& rServer)
{
    ::sfx2::LinkManager* pLinkManager = m_aDocument.GetLinkManager();
    ::sfx2::LinkManager* pLinkManager = m_pDocument->GetLinkManager();
    if (!pLinkManager)
        return;

@@ -319,7 +319,7 @@ void ScDocShell::UpdateLinks()
{
    typedef std::unordered_set<OUString> StrSetType;

    sfx2::LinkManager* pLinkManager = m_aDocument.GetLinkManager();
    sfx2::LinkManager* pLinkManager = m_pDocument->GetLinkManager();
    StrSetType aNames;

    // out with the no longer used links
@@ -343,23 +343,23 @@ void ScDocShell::UpdateLinks()

    // enter new links

    SCTAB nTabCount = m_aDocument.GetTableCount();
    SCTAB nTabCount = m_pDocument->GetTableCount();
    for (SCTAB i = 0; i < nTabCount; ++i)
    {
        if (!m_aDocument.IsLinked(i))
        if (!m_pDocument->IsLinked(i))
            continue;

        OUString aDocName = m_aDocument.GetLinkDoc(i);
        OUString aFltName = m_aDocument.GetLinkFlt(i);
        OUString aOptions = m_aDocument.GetLinkOpt(i);
        sal_uLong nRefresh  = m_aDocument.GetLinkRefreshDelay(i);
        OUString aDocName = m_pDocument->GetLinkDoc(i);
        OUString aFltName = m_pDocument->GetLinkFlt(i);
        OUString aOptions = m_pDocument->GetLinkOpt(i);
        sal_uLong nRefresh  = m_pDocument->GetLinkRefreshDelay(i);
        bool bThere = false;
        for (SCTAB j = 0; j < i && !bThere; ++j)                // several times in the document?
        {
            if (m_aDocument.IsLinked(j)
                    && m_aDocument.GetLinkDoc(j) == aDocName
                    && m_aDocument.GetLinkFlt(j) == aFltName
                    && m_aDocument.GetLinkOpt(j) == aOptions)
            if (m_pDocument->IsLinked(j)
                    && m_pDocument->GetLinkDoc(j) == aDocName
                    && m_pDocument->GetLinkFlt(j) == aFltName
                    && m_pDocument->GetLinkOpt(j) == aOptions)
                    // Ignore refresh delay in compare, it should be the
                    // same for identical links and we don't want dupes
                    // if it ain't.
@@ -385,7 +385,7 @@ void ScDocShell::UpdateLinks()

void ScDocShell::ReloadTabLinks()
{
    sfx2::LinkManager* pLinkManager = m_aDocument.GetLinkManager();
    sfx2::LinkManager* pLinkManager = m_pDocument->GetLinkManager();

    bool bAny = false;
    size_t nCount = pLinkManager->GetLinks().size();
@@ -409,7 +409,7 @@ void ScDocShell::ReloadTabLinks()
    if ( bAny )
    {
        //  Paint only once
        PostPaint( ScRange(0,0,0,m_aDocument.MaxCol(),m_aDocument.MaxRow(),MAXTAB),
        PostPaint( ScRange(0,0,0,m_pDocument->MaxCol(),m_pDocument->MaxRow(),MAXTAB),
                                    PaintPartFlags::Grid | PaintPartFlags::Top | PaintPartFlags::Left );

        SetDocumentModified();
@@ -418,7 +418,7 @@ void ScDocShell::ReloadTabLinks()

void ScDocShell::SetFormulaOptions( const ScFormulaOptions& rOpt, bool bForLoading )
{
    m_aDocument.SetGrammar( rOpt.GetFormulaSyntax() );
    m_pDocument->SetGrammar( rOpt.GetFormulaSyntax() );

    // This is nasty because it resets module globals from within a docshell!
    // For actual damage caused see fdo#82183 where an unconditional
@@ -466,7 +466,7 @@ void ScDocShell::SetFormulaOptions( const ScFormulaOptions& rOpt, bool bForLoadi
    }

    // Per document interpreter settings.
    m_aDocument.SetCalcConfig( rOpt.GetCalcConfig() );
    m_pDocument->SetCalcConfig( rOpt.GetCalcConfig() );
}

void ScDocShell::CheckConfigOptions()
diff --git a/sc/source/ui/docshell/docsh8.cxx b/sc/source/ui/docshell/docsh8.cxx
index 1f9368e..683ac2c 100644
--- a/sc/source/ui/docshell/docsh8.cxx
+++ b/sc/source/ui/docshell/docsh8.cxx
@@ -322,9 +322,9 @@ ErrCode ScDocShell::DBaseImport( const OUString& rFullFileName, rtl_TextEncoding
        if ( xMeta.is() )
            nColCount = xMeta->getColumnCount();    // this is the number of real columns

        if ( nColCount > m_aDocument.MaxCol()+1 )
        if ( nColCount > m_pDocument->MaxCol()+1 )
        {
            nColCount = m_aDocument.MaxCol()+1;
            nColCount = m_pDocument->MaxCol()+1;
            nErr = SCWARN_IMPORT_COLUMN_OVERFLOW;    // warning
        }

@@ -377,23 +377,23 @@ ErrCode ScDocShell::DBaseImport( const OUString& rFullFileName, rtl_TextEncoding
                    break;
            }

            m_aDocument.SetString( static_cast<SCCOL>(i), 0, 0, aHeader );
            m_pDocument->SetString( static_cast<SCCOL>(i), 0, 0, aHeader );
        }

        lcl_setScalesToColumns(m_aDocument, aScales);
        lcl_setScalesToColumns(*m_pDocument, aScales);

        SCROW nRow = 1;     // 0 is column titles
        bool bEnd = false;
        while ( !bEnd && xRowSet->next() )
        {
            if ( nRow <= m_aDocument.MaxRow() )
            if ( nRow <= m_pDocument->MaxRow() )
            {
                bool bSimpleRow = true;
                SCCOL nCol = 0;
                for (i=0; i<nColCount; i++)
                {
                    ScDatabaseDocUtil::StrData aStrData;
                    ScDatabaseDocUtil::PutData( m_aDocument, nCol, nRow, 0,
                    ScDatabaseDocUtil::PutData( *m_pDocument, nCol, nRow, 0,
                                                xRow, i+1, pTypeArr[i], false,
                                                &aStrData );

@@ -744,20 +744,20 @@ ErrCode ScDocShell::DBaseExport( const OUString& rFullFileName, rtl_TextEncoding
    SCCOL nFirstCol, nLastCol;
    SCROW  nFirstRow, nLastRow;
    SCTAB nTab = GetSaveTab();
    m_aDocument.GetDataStart( nTab, nFirstCol, nFirstRow );
    m_aDocument.GetCellArea( nTab, nLastCol, nLastRow );
    m_pDocument->GetDataStart( nTab, nFirstCol, nFirstRow );
    m_pDocument->GetCellArea( nTab, nLastCol, nLastRow );
    if ( nFirstCol > nLastCol )
        nFirstCol = nLastCol;
    if ( nFirstRow > nLastRow )
        nFirstRow = nLastRow;
    ScProgress aProgress( this, ScResId( STR_SAVE_DOC ),
                                                    nLastRow - nFirstRow, true );
    SvNumberFormatter* pNumFmt = m_aDocument.GetFormatTable();
    SvNumberFormatter* pNumFmt = m_pDocument->GetFormatTable();

    bool bHasFieldNames = true;
    for ( SCCOL nDocCol = nFirstCol; nDocCol <= nLastCol && bHasFieldNames; nDocCol++ )
    {   // only Strings in first row => are field names
        if ( !m_aDocument.HasStringData( nDocCol, nFirstRow, nTab ) )
        if ( !m_pDocument->HasStringData( nDocCol, nFirstRow, nTab ) )
            bHasFieldNames = false;
    }

@@ -774,7 +774,7 @@ ErrCode ScDocShell::DBaseExport( const OUString& rFullFileName, rtl_TextEncoding
                        bHasMemo, eCharSet );
    // also needed for exception catch
    SCROW nDocRow = 0;
    ScFieldEditEngine aEditEngine(&m_aDocument, m_aDocument.GetEditPool());
    ScFieldEditEngine aEditEngine(m_pDocument.get(), m_pDocument->GetEditPool());
    OUString aString;

    try
@@ -900,7 +900,7 @@ ErrCode ScDocShell::DBaseExport( const OUString& rFullFileName, rtl_TextEncoding
                {
                    case sdbc::DataType::LONGVARCHAR:
                    {
                        ScRefCellValue aCell(m_aDocument, ScAddress(nDocCol, nDocRow, nTab));
                        ScRefCellValue aCell(*m_pDocument, ScAddress(nDocCol, nDocRow, nTab));
                        if (!aCell.isEmpty())
                        {
                            if (aCell.meType == CELLTYPE_EDIT)
@@ -910,7 +910,7 @@ ErrCode ScDocShell::DBaseExport( const OUString& rFullFileName, rtl_TextEncoding
                            else
                            {
                                lcl_getLongVarCharString(
                                    aString, m_aDocument, nDocCol, nDocRow, nTab, *pNumFmt);
                                    aString, *m_pDocument, nDocCol, nDocRow, nTab, *pNumFmt);
                            }
                            xRowUpdate->updateString( nCol+1, aString );
                        }
@@ -920,7 +920,7 @@ ErrCode ScDocShell::DBaseExport( const OUString& rFullFileName, rtl_TextEncoding
                    break;

                    case sdbc::DataType::VARCHAR:
                        aString = m_aDocument.GetString(nDocCol, nDocRow, nTab);
                        aString = m_pDocument->GetString(nDocCol, nDocRow, nTab);
                        xRowUpdate->updateString( nCol+1, aString );
                        if ( nErr == ERRCODE_NONE && pColLengths[nCol] < aString.getLength() )
                            nErr = SCWARN_EXPORT_DATALOST;
@@ -928,16 +928,16 @@ ErrCode ScDocShell::DBaseExport( const OUString& rFullFileName, rtl_TextEncoding

                    case sdbc::DataType::DATE:
                        {
                            fVal = m_aDocument.GetValue( nDocCol, nDocRow, nTab );
                            fVal = m_pDocument->GetValue( nDocCol, nDocRow, nTab );
                            // differentiate between 0 with value and 0 no-value
                            bool bIsNull = (fVal == 0.0);
                            if ( bIsNull )
                                bIsNull = !m_aDocument.HasValueData( nDocCol, nDocRow, nTab );
                                bIsNull = !m_pDocument->HasValueData( nDocCol, nDocRow, nTab );
                            if ( bIsNull )
                            {
                                xRowUpdate->updateNull( nCol+1 );
                                if ( nErr == ERRCODE_NONE &&
                                        m_aDocument.HasStringData( nDocCol, nDocRow, nTab ) )
                                        m_pDocument->HasStringData( nDocCol, nDocRow, nTab ) )
                                    nErr = SCWARN_EXPORT_DATALOST;
                            }
                            else
@@ -951,9 +951,9 @@ ErrCode ScDocShell::DBaseExport( const OUString& rFullFileName, rtl_TextEncoding

                    case sdbc::DataType::DECIMAL:
                    case sdbc::DataType::BIT:
                        fVal = m_aDocument.GetValue( nDocCol, nDocRow, nTab );
                        fVal = m_pDocument->GetValue( nDocCol, nDocRow, nTab );
                        if ( fVal == 0.0 && nErr == ERRCODE_NONE &&
                                            m_aDocument.HasStringData( nDocCol, nDocRow, nTab ) )
                                            m_pDocument->HasStringData( nDocCol, nDocRow, nTab ) )
                            nErr = SCWARN_EXPORT_DATALOST;
                        if ( pColTypes[nCol] == sdbc::DataType::BIT )
                            xRowUpdate->updateBoolean( nCol+1, ( fVal != 0.0 ) );
@@ -965,7 +965,7 @@ ErrCode ScDocShell::DBaseExport( const OUString& rFullFileName, rtl_TextEncoding
                        OSL_FAIL( "ScDocShell::DBaseExport: unknown FieldType" );
                        if ( nErr == ERRCODE_NONE )
                            nErr = SCWARN_EXPORT_DATALOST;
                        fVal = m_aDocument.GetValue( nDocCol, nDocRow, nTab );
                        fVal = m_pDocument->GetValue( nDocCol, nDocRow, nTab );
                        xRowUpdate->updateDouble( nCol+1, fVal );
                }
            }
@@ -996,7 +996,7 @@ ErrCode ScDocShell::DBaseExport( const OUString& rFullFileName, rtl_TextEncoding
            SCCOL nDocCol = nFirstCol;
            const sal_Int32* pColTypes = aColTypes.getConstArray();
            const sal_Int32* pColLengths = aColLengths.getConstArray();
            ScHorizontalCellIterator aIter( m_aDocument, nTab, nFirstCol,
            ScHorizontalCellIterator aIter( *m_pDocument, nTab, nFirstCol,
                    nDocRow, nLastCol, nDocRow);
            bool bTest = true;
            while (bTest)
@@ -1013,12 +1013,12 @@ ErrCode ScDocShell::DBaseExport( const OUString& rFullFileName, rtl_TextEncoding
                                lcl_getLongVarCharEditString(aString, *pCell, aEditEngine);
                            else
                                lcl_getLongVarCharString(
                                    aString, m_aDocument, nDocCol, nDocRow, nTab, *pNumFmt);
                                    aString, *m_pDocument, nDocCol, nDocRow, nTab, *pNumFmt);
                        }
                        break;

                    case sdbc::DataType::VARCHAR:
                        aString = m_aDocument.GetString(nDocCol, nDocRow, nTab);
                        aString = m_pDocument->GetString(nDocCol, nDocRow, nTab);
                        break;

                    // NOTE: length of DECIMAL fields doesn't need to be
diff --git a/sc/source/ui/inc/docsh.hxx b/sc/source/ui/inc/docsh.hxx
index 20f326a..a2655c0 100644
--- a/sc/source/ui/inc/docsh.hxx
+++ b/sc/source/ui/inc/docsh.hxx
@@ -79,7 +79,7 @@ extern "C" SAL_DLLPUBLIC_EXPORT bool TestImportDBF(SvStream &rStream);

class SC_DLLPUBLIC ScDocShell final: public SfxObjectShell, public SfxListener
{
    ScDocument          m_aDocument;
    std::shared_ptr<ScDocument> m_pDocument;

    OUString            m_aDdeTextFmt;

@@ -217,8 +217,8 @@ public:

    void    GetDocStat( ScDocStat& rDocStat );

    const ScDocument& GetDocument() const { return m_aDocument; }
    ScDocument&     GetDocument()   { return m_aDocument; }
    const ScDocument& GetDocument() const { return *m_pDocument; }
    ScDocument&     GetDocument()   { return *m_pDocument; }
    ScDocFunc&      GetDocFunc()    { return *m_pDocFunc; }

    css::uno::Reference<css::datatransfer::XTransferable2> const & GetClipData() const { return m_xClipData; }