tdf#127205 split Desktop::terminate process

Trying to somehow keep stuff correctly alive, truned out to be
rather futile. Originally I tried the same way Caolan did in the
attached patch to tdf#88985, when he finally settled on adding a
special terminate listener.

But this is not enough to handle in-process scripted extensions,
like Java, Python or even Basic macros themself.

So this separates the module shutdown and SfxApplication cleanup
from the rest of the terminate call.

Change-Id: Ice59816080c922a17511b68afe59348a662600c9
Reviewed-on: https://gerrit.libreoffice.org/c/core/+/88835
Tested-by: Jenkins
Reviewed-by: Jan-Marek Glogowski <glogow@fbihome.de>
diff --git a/desktop/inc/app.hxx b/desktop/inc/app.hxx
index 1dc5f8a..4e61b58 100644
--- a/desktop/inc/app.hxx
+++ b/desktop/inc/app.hxx
@@ -75,6 +75,7 @@
        virtual void            InitFinished() override;
        virtual void            DeInit() override;
        virtual bool            QueryExit() override;
        virtual void            Shutdown() override;
        virtual void            Exception(ExceptionCategory nCategory) override;
        virtual void            OverrideSystemSettings( AllSettings& rSettings ) override;
        virtual void            AppEvent( const ApplicationEvent& rAppEvent ) override;
diff --git a/desktop/source/app/app.cxx b/desktop/source/app/app.cxx
index 6d0fe6e..c008854 100644
--- a/desktop/source/app/app.cxx
+++ b/desktop/source/app/app.cxx
@@ -76,6 +76,7 @@
#include <com/sun/star/office/Quickstart.hpp>
#include <com/sun/star/system/XSystemShellExecute.hpp>
#include <com/sun/star/system/SystemShellExecute.hpp>
#include <com/sun/star/frame/XDesktopInternal.hpp>

#include <desktop/exithelper.h>
#include <sal/log.hxx>
@@ -606,6 +607,13 @@
    return bExit;
}

void Desktop::Shutdown()
{
    Reference<XDesktop2> xDesktop = css::frame::Desktop::create(::comphelper::getProcessComponentContext());
    Reference<XDesktopInternal> xDesktopInternal(xDesktop, UNO_QUERY_THROW);
    xDesktopInternal->shutdown();
}

void Desktop::HandleBootstrapPathErrors( ::utl::Bootstrap::Status aBootstrapStatus, const OUString& aDiagnosticMessage )
{
    if ( aBootstrapStatus != ::utl::Bootstrap::DATA_OK )
diff --git a/framework/inc/services/desktop.hxx b/framework/inc/services/desktop.hxx
index ff578c4..1f0f791 100644
--- a/framework/inc/services/desktop.hxx
+++ b/framework/inc/services/desktop.hxx
@@ -30,6 +30,7 @@
#include <com/sun/star/frame/XUntitledNumbers.hpp>
#include <com/sun/star/frame/XController.hpp>
#include <com/sun/star/frame/XDesktop2.hpp>
#include <com/sun/star/frame/XDesktopInternal.hpp>
#include <com/sun/star/frame/XTerminateListener.hpp>
#include <com/sun/star/frame/XTask.hpp>
#include <com/sun/star/frame/XFramesSupplier.hpp>
@@ -89,6 +90,7 @@
typedef cppu::WeakComponentImplHelper<
           css::lang::XServiceInfo              ,
           css::frame::XDesktop2                ,
           css::frame::XDesktopInternal,
           css::frame::XTasksSupplier           ,
           css::frame::XDispatchResultListener  ,   // => XEventListener
           css::task::XInteractionHandler       ,
@@ -283,6 +285,8 @@
        /// @throws css::uno::RuntimeException
        bool terminateQuickstarterToo();

        virtual void SAL_CALL shutdown() override;

    private:

        //  OPropertySetHelper
@@ -311,14 +315,11 @@
         *          Those list will be used to inform all called listener
         *          about cancel this termination request.
         *
         *  @param  [out] bVeto
         *          will be true if at least one listener threw a veto exception;
         *          false otherwise.
         *  @return true if no one vetoed the termination.
         *
         *  @see    impl_sendCancelTerminationEvent()
         */
        void impl_sendQueryTerminationEvent(TTerminateListenerList& lCalledListener,
                                            bool&             bVeto          );
        bool impl_sendQueryTerminationEvent(TTerminateListenerList& lCalledListener);

        /** calls cancelTermination() on every termination listener
         *  where queryTermination() was called before.
@@ -373,10 +374,14 @@

        mutable TransactionManager    m_aTransactionManager;

        /** check flag to protect against multiple terminate runs
          */
        bool m_bIsTerminated;

        /** check flag to protect us against dispose before terminate!
          *   see dispose() for further information!
          */
        bool m_bIsTerminated;
        bool m_bIsShutdown;

        /** when true, the call came from session manager
          *   the method is Desktop::terminateQuickstarterToo()
diff --git a/framework/source/services/desktop.cxx b/framework/source/services/desktop.cxx
index 8b20e59..acf422ac 100644
--- a/framework/source/services/desktop.cxx
+++ b/framework/source/services/desktop.cxx
@@ -146,7 +146,8 @@
        :   Desktop_BASE            ( m_aMutex )
        ,   cppu::OPropertySetHelper( cppu::WeakComponentImplHelperBase::rBHelper   )
        // Init member
        ,   m_bIsTerminated         ( false                                     )   // see dispose() for further information!
    , m_bIsTerminated(false)
    , m_bIsShutdown(false)   // see dispose() for further information!
        ,   m_bSession              ( false                                         )
        ,   m_xContext              ( xContext                                      )
        ,   m_aChildTaskContainer   (                                               )
@@ -175,7 +176,7 @@
*//*-*************************************************************************************************************/
Desktop::~Desktop()
{
    SAL_WARN_IF( !m_bIsTerminated, "fwk.desktop", "Desktop not terminated before being destructed" );
    SAL_WARN_IF(!m_bIsShutdown, "fwk.desktop", "Desktop not terminated before being destructed");
    SAL_WARN_IF( m_aTransactionManager.getWorkingMode()!=E_CLOSE, "fwk.desktop", "Desktop::~Desktop(): Who forgot to dispose this service?" );
}

@@ -198,8 +199,10 @@
sal_Bool SAL_CALL Desktop::terminate()
{
    TransactionGuard aTransaction( m_aTransactionManager, E_HARDEXCEPTIONS );
    SolarMutexResettableGuard aGuard;

    SolarMutexClearableGuard aReadLock;
    if (m_bIsTerminated)
        return true;

    css::uno::Reference< css::frame::XTerminateListener > xPipeTerminator    = m_xPipeTerminator;
    css::uno::Reference< css::frame::XTerminateListener > xQuickLauncher     = m_xQuickLauncher;
@@ -209,35 +212,22 @@

    css::lang::EventObject                                aEvent             ( static_cast< ::cppu::OWeakObject* >(this) );
    bool                                                  bAskQuickStart     = !m_bSuspendQuickstartVeto;
    const bool bRestartableMainLoop = Application::IsEventTestingModeEnabled() ||
                                      comphelper::LibreOfficeKit::isActive();
    aGuard.clear();

    aReadLock.clear();

    // try to close all open frames.
    // Allow using of any UI ... because Desktop.terminate() was designed as UI functionality in the past.
    bool bRestartableMainLoop = Application::IsEventTestingModeEnabled() ||
                                comphelper::LibreOfficeKit::isActive();
    bool bFramesClosed = impl_closeFrames(!bRestartableMainLoop);

    // Ask normal terminate listener. They could stop terminating the process.
    // Ask normal terminate listener. They could veto terminating the process.
    Desktop::TTerminateListenerList lCalledTerminationListener;
    bool bVeto = false;
    impl_sendQueryTerminationEvent(lCalledTerminationListener, bVeto);
    if ( bVeto )
    if (!impl_sendQueryTerminationEvent(lCalledTerminationListener))
    {
        impl_sendCancelTerminationEvent(lCalledTerminationListener);
        return false;
    }

    if (bRestartableMainLoop)
    {
#ifndef IOS // or ANDROID?
        // In the iOS app, posting the ImplQuitMsg user event will be too late, it will not be handled during the
        // lifetime of the current document, but handled for the next document opened, which thus will break horribly.
        Application::Quit();
#endif
        return true;
    }
    if ( ! bFramesClosed )
    // try to close all open frames
    if (!impl_closeFrames(!bRestartableMainLoop))
    {
        impl_sendCancelTerminationEvent(lCalledTerminationListener);
        return false;
@@ -259,7 +249,6 @@
    // but some can be dangerous. E.g. it would be dangerous if we close our pipe
    // and don't terminate in real because another listener throws a veto exception .-)

    bool bTerminate = false;
    try
    {
        if( bAskQuickStart && xQuickLauncher.is() )
@@ -291,42 +280,33 @@
            xSfxTerminator->queryTermination( aEvent );
            lCalledTerminationListener.push_back( xSfxTerminator );
        }

        bTerminate = true;
    }
    catch(const css::frame::TerminationVetoException&)
    {
        bTerminate = false;
        impl_sendCancelTerminationEvent(lCalledTerminationListener);
        return false;
    }

    if ( ! bTerminate )
        impl_sendCancelTerminationEvent(lCalledTerminationListener);
    else
    aGuard.reset();
    if (m_bIsTerminated)
        return true;
    m_bIsTerminated = true;

    if (!bRestartableMainLoop)
    {
        // "Protect" us against dispose before terminate calls!
        // see dispose() for further information.
        /* SAFE AREA --------------------------------------------------------------------------------------- */
        SolarMutexClearableGuard aWriteLock;
        CrashReporter::addKeyValue("ShutDown", OUString::boolean(true), CrashReporter::Write);
        m_bIsTerminated = true;
        aWriteLock.clear();
        /* UNSAFE AREA ------------------------------------------------------------------------------------- */

        // The clipboard listener needs to be the first. It can create copies of the
        // existing document which needs basically all the available infrastructure.
        impl_sendTerminateToClipboard();
        {
            SolarMutexResettableGuard aGuard;
            impl_sendTerminateToClipboard();
            aGuard.clear();
            SolarMutexReleaser aReleaser;
            impl_sendNotifyTerminationEvent();
            aGuard.reset();
            Scheduler::ProcessEventsToIdle();
        }
        Scheduler::ProcessEventsToIdle();

        if( bAskQuickStart && xQuickLauncher.is() )
        {
            xQuickLauncher->notifyTermination( aEvent );
        }

        if ( xStarBasicQuitGuard.is() )
            xStarBasicQuitGuard->notifyTermination( aEvent );
@@ -337,22 +317,44 @@
        if ( xPipeTerminator.is() )
            xPipeTerminator->notifyTermination( aEvent );

        // we need a copy here as the notifyTermination call might cause a removeTerminateListener call
        std::vector< css::uno::Reference<css::frame::XTerminateListener> > xComponentDllListeners;
        xComponentDllListeners.swap(m_xComponentDllListeners);
        for (auto& xListener : xComponentDllListeners)
        {
            xListener->notifyTermination(aEvent);
        }
        xComponentDllListeners.clear();

        // Must be really the last listener to be called.
        // Because it shutdown the whole process asynchronous !
        if ( xSfxTerminator.is() )
            xSfxTerminator->notifyTermination( aEvent );
        // further termination is postponed to shutdown
    }
    else
        m_bIsShutdown = true;

    return bTerminate;
#ifndef IOS // or ANDROID?
    aGuard.clear();
    // In the iOS app, posting the ImplQuitMsg user event will be too late, it will not be handled during the
    // lifetime of the current document, but handled for the next document opened, which thus will break horribly.
    Application::Quit();
#endif

    return true;
}

void Desktop::shutdown()
{
    TransactionGuard aTransaction(m_aTransactionManager, E_HARDEXCEPTIONS);
    SolarMutexGuard aGuard;

    if (m_bIsShutdown)
        return;
    m_bIsShutdown = true;

    css::uno::Reference<css::frame::XTerminateListener> xSfxTerminator = m_xSfxTerminator;
    css::lang::EventObject aEvent(static_cast<::cppu::OWeakObject* >(this));

    // we need a copy here as the notifyTermination call might cause a removeTerminateListener call
    std::vector< css::uno::Reference<css::frame::XTerminateListener> > xComponentDllListeners;
    xComponentDllListeners.swap(m_xComponentDllListeners);
    for (auto& xListener : xComponentDllListeners)
        xListener->notifyTermination(aEvent);
    xComponentDllListeners.clear();

    // Must be really the last listener to be called.
    // Because it shuts down the whole process asynchronous!
    if (xSfxTerminator.is())
        xSfxTerminator->notifyTermination(aEvent);
}

namespace
@@ -1058,7 +1060,7 @@

    // But if you just ignore the assertion (which happens in unit
    // tests for instance in sc/qa/unit) nothing bad happens.
    SAL_WARN_IF( !m_bIsTerminated, "fwk.desktop", "Desktop disposed before terminating it" );
    SAL_WARN_IF(!m_bIsShutdown, "fwk.desktop", "Desktop disposed before terminating it");

    {
        SolarMutexGuard aWriteLock;
@@ -1555,16 +1557,13 @@
    return xComponent;
}

void Desktop::impl_sendQueryTerminationEvent(Desktop::TTerminateListenerList& lCalledListener,
                                             bool&                      bVeto          )
bool Desktop::impl_sendQueryTerminationEvent(Desktop::TTerminateListenerList& lCalledListener)
{
    bVeto = false;

    TransactionGuard aTransaction( m_aTransactionManager, E_HARDEXCEPTIONS );

    ::cppu::OInterfaceContainerHelper* pContainer = m_aListenerContainer.getContainer( cppu::UnoType<css::frame::XTerminateListener>::get());
    if ( ! pContainer )
        return;
        return true;

    css::lang::EventObject aEvent( static_cast< ::cppu::OWeakObject* >(this) );

@@ -1581,9 +1580,8 @@
        }
        catch( const css::frame::TerminationVetoException& )
        {
            // first veto will stop notification loop.
            bVeto = true;
            return;
            // first veto will stop the query loop.
            return false;
        }
        catch( const css::uno::Exception& )
        {
@@ -1593,6 +1591,8 @@
            aIterator.remove();
        }
    }

    return true;
}

void Desktop::impl_sendCancelTerminationEvent(const Desktop::TTerminateListenerList& lCalledListener)
diff --git a/include/vcl/svapp.hxx b/include/vcl/svapp.hxx
index 0fa4b08..27aa29d 100644
--- a/include/vcl/svapp.hxx
+++ b/include/vcl/svapp.hxx
@@ -354,6 +354,8 @@
    */
    virtual bool                QueryExit();

    virtual void                Shutdown();

    /** @name Change Notification Functions

        Functions that notify when changes occur in the application.
diff --git a/offapi/UnoApi_offapi.mk b/offapi/UnoApi_offapi.mk
index 12ab8e20..0453d1f 100644
--- a/offapi/UnoApi_offapi.mk
+++ b/offapi/UnoApi_offapi.mk
@@ -2604,6 +2604,7 @@
	XControllerBorder \
	XDesktop \
	XDesktop2 \
	XDesktopInternal \
	XDesktopTask \
	XDispatch \
	XDispatchHelper \
diff --git a/offapi/com/sun/star/frame/XDesktopInternal.idl b/offapi/com/sun/star/frame/XDesktopInternal.idl
new file mode 100644
index 0000000..85dcad9
--- /dev/null
+++ b/offapi/com/sun/star/frame/XDesktopInternal.idl
@@ -0,0 +1,28 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */
#ifndef __com_sun_star_frame_XDesktopInternal_idl__
#define __com_sun_star_frame_XDesktopInternal_idl__

module com {  module sun {  module star {  module frame {

/**
 * @internal
 */
interface XDesktopInternal
{
    /** clean up XDesktop instances after termination, when quit from Application::Execute
     */
    void shutdown();
};

}; }; }; };

#endif

/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */
diff --git a/vcl/source/app/svapp.cxx b/vcl/source/app/svapp.cxx
index b6b5917..1f9a0e1 100644
--- a/vcl/source/app/svapp.cxx
+++ b/vcl/source/app/svapp.cxx
@@ -186,6 +186,10 @@
        return true;
}

void Application::Shutdown()
{
}

void Application::Init()
{
}
@@ -429,6 +433,8 @@
        Application::Yield();

    pSVData->maAppData.mbInAppExecute = false;

    GetpApp()->Shutdown();
}

static bool ImplYield(bool i_bWait, bool i_bAllEvents)
@@ -514,11 +520,12 @@

IMPL_STATIC_LINK_NOARG( ImplSVAppData, ImplQuitMsg, void*, void )
{
    ImplGetSVData()->maAppData.mbAppQuit = true;
    assert(ImplGetSVData()->maAppData.mbAppQuit);
}

void Application::Quit()
{
    ImplGetSVData()->maAppData.mbAppQuit = true;
    Application::PostUserEvent( LINK( nullptr, ImplSVAppData, ImplQuitMsg ) );
}