[Libreoffice-commits] core.git: Branch 'private/jmux/mm-cleanup' - 188 commits - accessibility/inc accessibility/source avmedia/source basctl/source bridges/source compilerplugins/clang config_host/config_cups.h.in configure.ac connectivity/source cui/source desktop/inc desktop/source drawinglayer/source dtrans/source editeng/source embeddedobj/source embedserv/source extensions/source external/libxmlsec extras/source filter/source fpicker/source framework/inc framework/source helpcontent2 icon-themes/galaxy include/drawinglayer include/LibreOfficeKit include/o3tl include/postx.h include/sfx2 include/toolkit include/tools include/vcl libreofficekit/source lingucomponent/Library_MacOSXSpell.mk offapi/com officecfg/registry readlicense_oo/license sal/cppunittester sal/rtl sc/CppunitTest_sc_ucalc.mk sc/qa sc/source sdext/source sd/qa sd/source sfx2/sdi sfx2/source solenv/gbuild soltools/mkdepend sot/source starmath/qa svgio/source svtools/inc svtools/source svx/source sw/inc sw/ooxmlexport_setup.mk sw/qa sw/source toolkit/Library_tk.mk toolkit/source tools/source translations ucb/CppunitTest_ucb_webdav_local_neon.mk ucb/Module_ucb.mk ucb/qa vcl/headless vcl/inc vcl/Library_vcl.mk vcl/Library_vclplug_gen.mk vcl/opengl vcl/osx vcl/source vcl/unx vcl/win winaccessibility/source writerfilter/source xmlsecurity/source

Jan-Marek Glogowski glogow at fbihome.de
Wed Jan 27 05:53:05 PST 2016


Rebased ref, commits from common ancestor:
commit 8ebcd0f4272dbac1809752654e269c0683705f70
Author: Jan-Marek Glogowski <glogow at fbihome.de>
Date:   Wed Jan 27 14:41:35 2016 +0100

    MM: remove multiple unneeded indention levels
    
    Change-Id: Ia363904d3c3fbabdb7aa0dd9aa0715d7d6982f85

diff --git a/sw/source/uibase/dbui/dbmgr.cxx b/sw/source/uibase/dbui/dbmgr.cxx
index 57c68b1..d3a4827 100644
--- a/sw/source/uibase/dbui/dbmgr.cxx
+++ b/sw/source/uibase/dbui/dbmgr.cxx
@@ -1103,474 +1103,470 @@ bool SwDBManager::MergeMailFiles(SwWrtShell* pSourceShell,
     rtl_TextEncoding                    sMailEncoding = ::osl_getThreadTextEncoding();
 
     uno::Reference< beans::XPropertySet > xColumnProp;
+
+    // Check for (mandatory) email or (optional) filename column
+    SwDBFormatData aColumnDBFormat;
+    bool bColumnName = !rMergeDescriptor.sDBcolumn.isEmpty();
+    if( ! bColumnName )
     {
-        // Check for (mandatory) email or (optional) filename column
-        SwDBFormatData aColumnDBFormat;
-        bool bColumnName = !rMergeDescriptor.sDBcolumn.isEmpty();
-        if( ! bColumnName )
-        {
-            if( bMT_EMAIL )
-                return false;
-        }
-        else
-        {
-            uno::Reference< sdbcx::XColumnsSupplier > xColsSupp( pImpl->pMergeData->xResultSet, uno::UNO_QUERY );
-            uno::Reference<container::XNameAccess> xCols = xColsSupp->getColumns();
-            if( !xCols->hasByName( rMergeDescriptor.sDBcolumn ) )
-                return false;
-            uno::Any aCol = xCols->getByName( rMergeDescriptor.sDBcolumn );
-            aCol >>= xColumnProp;
+        if( bMT_EMAIL )
+            return false;
+    }
+    else
+    {
+        uno::Reference< sdbcx::XColumnsSupplier > xColsSupp( pImpl->pMergeData->xResultSet, uno::UNO_QUERY );
+        uno::Reference<container::XNameAccess> xCols = xColsSupp->getColumns();
+        if( !xCols->hasByName( rMergeDescriptor.sDBcolumn ) )
+            return false;
+        uno::Any aCol = xCols->getByName( rMergeDescriptor.sDBcolumn );
+        aCol >>= xColumnProp;
 
-            aColumnDBFormat.xFormatter = pImpl->pMergeData->xFormatter;
-            aColumnDBFormat.aNullDate  = pImpl->pMergeData->aNullDate;
+        aColumnDBFormat.xFormatter = pImpl->pMergeData->xFormatter;
+        aColumnDBFormat.aNullDate  = pImpl->pMergeData->aNullDate;
 
-            if( bMT_EMAIL )
+        if( bMT_EMAIL )
+        {
+            xMailDispatcher.set( new MailDispatcher(rMergeDescriptor.xSmtpServer));
+            if(!rMergeDescriptor.bSendAsAttachment && rMergeDescriptor.bSendAsHTML)
             {
-                xMailDispatcher.set( new MailDispatcher(rMergeDescriptor.xSmtpServer));
-                if(!rMergeDescriptor.bSendAsAttachment && rMergeDescriptor.bSendAsHTML)
-                {
-                    sMailBodyMimeType = "text/html; charset=";
-                    sMailBodyMimeType += OUString::createFromAscii(
-                                        rtl_getBestMimeCharsetFromTextEncoding( sMailEncoding ));
-                    SvxHtmlOptions& rHtmlOptions = SvxHtmlOptions::Get();
-                    sMailEncoding = rHtmlOptions.GetTextEncoding();
-                }
-                else
-                    sMailBodyMimeType = "text/plain; charset=UTF-8; format=flowed";
+                sMailBodyMimeType = "text/html; charset=";
+                sMailBodyMimeType += OUString::createFromAscii(
+                                    rtl_getBestMimeCharsetFromTextEncoding( sMailEncoding ));
+                SvxHtmlOptions& rHtmlOptions = SvxHtmlOptions::Get();
+                sMailEncoding = rHtmlOptions.GetTextEncoding();
             }
+            else
+                sMailBodyMimeType = "text/plain; charset=UTF-8; format=flowed";
         }
+    }
+
+    SwDocShell  *pSourceDocSh = pSourceShell->GetView().GetDocShell();
 
-        SwDocShell  *pSourceDocSh = pSourceShell->GetView().GetDocShell();
+    // setup the output format
+    const SfxFilter* pStoreToFilter = SwIoSystem::GetFileFilter(
+        pSourceDocSh->GetMedium()->GetURLObject().GetMainURL(INetURLObject::NO_DECODE));
+    SfxFilterContainer* pFilterContainer = SwDocShell::Factory().GetFilterContainer();
+    const OUString* pStoreToFilterOptions = nullptr;
 
+    // if a save_to filter is set then use it - otherwise use the default
+    if( bMT_EMAIL && !rMergeDescriptor.bSendAsAttachment )
+    {
+        OUString sExtension = rMergeDescriptor.bSendAsHTML ? OUString("html") : OUString("txt");
+        pStoreToFilter = pFilterContainer->GetFilter4Extension(sExtension, SfxFilterFlags::EXPORT);
+    }
+    else if( !rMergeDescriptor.sSaveToFilter.isEmpty())
+    {
+        const SfxFilter* pFilter =
+                pFilterContainer->GetFilter4FilterName( rMergeDescriptor.sSaveToFilter );
+        if(pFilter)
         {
-            // setup the output format
-            const SfxFilter* pStoreToFilter = SwIoSystem::GetFileFilter(
-                pSourceDocSh->GetMedium()->GetURLObject().GetMainURL(INetURLObject::NO_DECODE));
-            SfxFilterContainer* pFilterContainer = SwDocShell::Factory().GetFilterContainer();
-            const OUString* pStoreToFilterOptions = nullptr;
+            pStoreToFilter = pFilter;
+            if(!rMergeDescriptor.sSaveToFilterOptions.isEmpty())
+                pStoreToFilterOptions = &rMergeDescriptor.sSaveToFilterOptions;
+        }
+    }
+    const bool bIsPDFeport = pStoreToFilter && pStoreToFilter->GetFilterName() == "writer_pdf_Export";
 
-            // if a save_to filter is set then use it - otherwise use the default
-            if( bMT_EMAIL && !rMergeDescriptor.bSendAsAttachment )
-            {
-                OUString sExtension = rMergeDescriptor.bSendAsHTML ? OUString("html") : OUString("txt");
-                pStoreToFilter = pFilterContainer->GetFilter4Extension(sExtension, SfxFilterFlags::EXPORT);
-            }
-            else if( !rMergeDescriptor.sSaveToFilter.isEmpty())
-            {
-                const SfxFilter* pFilter =
-                        pFilterContainer->GetFilter4FilterName( rMergeDescriptor.sSaveToFilter );
-                if(pFilter)
-                {
-                    pStoreToFilter = pFilter;
-                    if(!rMergeDescriptor.sSaveToFilterOptions.isEmpty())
-                        pStoreToFilterOptions = &rMergeDescriptor.sSaveToFilterOptions;
-                }
-            }
-            const bool bIsPDFeport = pStoreToFilter && pStoreToFilter->GetFilterName() == "writer_pdf_Export";
+    const sal_Int16 nWantedDBrecords = pSourceDocSh->GetDoc()->GetDocumentFieldsManager().WantedDBrecords();
 
-            const sal_Int16 nWantedDBrecords = pSourceDocSh->GetDoc()->GetDocumentFieldsManager().WantedDBrecords();
+    m_aMergeStatus = MergeStatus::OK;
 
-            m_aMergeStatus = MergeStatus::OK;
+    SwWrtShell*       pTargetShell = nullptr;
+    SwDoc*            pTargetDoc   = nullptr;
+    SwView*           pTargetView  = nullptr;
+    SfxObjectShellRef xTargetDocShell;
 
-            SwWrtShell*       pTargetShell = nullptr;
-            SwDoc*            pTargetDoc   = nullptr;
-            SwView*           pTargetView  = nullptr;
-            SfxObjectShellRef xTargetDocShell;
+    std::unique_ptr< utl::TempFile > aTempFile;
+    sal_uInt16 nStartingPageNo = 0;
 
-            std::unique_ptr< utl::TempFile > aTempFile;
-            sal_uInt16 nStartingPageNo = 0;
+    vcl::Window *pSourceWindow = nullptr;
+    VclPtr<CancelableDialog> pProgressDlg;
 
-            vcl::Window *pSourceWindow = nullptr;
-            VclPtr<CancelableDialog> pProgressDlg;
+    if( !bIsMergeSilent )
+    {
+        // construct the process dialog
+        pSourceWindow = &pSourceShell->GetView().GetEditWin();
+        if( !pParent )
+            pParent = pSourceWindow;
+        if( !bMT_PRINTER )
+            pProgressDlg = VclPtr<CreateMonitor>::Create(
+                pParent, pParent != pSourceWindow );
+        else {
+            pProgressDlg = VclPtr<PrintMonitor>::Create(
+                pParent, pParent != pSourceWindow,
+                PrintMonitor::MONITOR_TYPE_PRINT );
+            static_cast<PrintMonitor*>( pProgressDlg.get() )->SetText(
+                pSourceDocSh->GetTitle(22) );
+        }
+        pProgressDlg->SetCancelHdl( LINK(this, SwDBManager, PrtCancelHdl) );
+        pProgressDlg->Show();
 
-            if( !bIsMergeSilent )
+        RESCHEDULE_GUI;
+    }
+
+    if( bCreateSingleFile )
+    {
+        // create a target docshell to put the merged document into
+        xTargetDocShell = lcl_CreateWorkingDocument( WorkingDocType::TARGET,
+            pSourceDocSh->GetDoc(), bMT_SHELL ? pSourceWindow : nullptr,
+            nullptr, &pTargetView, &pTargetShell, &pTargetDoc );
+        if (nMaxDumpDocs)
+            lcl_SaveDebugDoc( xTargetDocShell, "MergeDoc" );
+
+        // determine the page style and number used at the start of the source document
+        pSourceShell->SttEndDoc(true);
+        nStartingPageNo = pSourceShell->GetVirtPageNum();
+    }
+
+    // Progress, to prohibit KeyInputs
+    SfxProgress aProgress(pSourceDocSh, ::aEmptyOUStr, 1);
+
+    // lock all dispatchers
+    SfxViewFrame* pViewFrame = SfxViewFrame::GetFirst(pSourceDocSh);
+    while (pViewFrame)
+    {
+        pViewFrame->GetDispatcher()->Lock(true);
+        pViewFrame = SfxViewFrame::GetNext(*pViewFrame, pSourceDocSh);
+    }
+
+    sal_Int32 nDocNo = 1;
+    sal_Int32 nDocCount = 0;
+    // For single file mode, the number of pages in the target document so far, which is used
+    // by AppendDoc() to adjust position of page-bound objects. Getting this information directly
+    // from the target doc would require repeated layouts of the doc, which is expensive, but
+    // it can be manually computed from the source documents (for which we do layouts, so the page
+    // count is known, and there is a blank page between each of them in the target document).
+    int targetDocPageCount = 0;
+    if( !bIsMergeSilent && !bMT_PRINTER &&
+            lcl_getCountFromResultSet( nDocCount, pImpl->pMergeData->xResultSet ) )
+        static_cast<CreateMonitor*>( pProgressDlg.get() )->SetTotalCount( nDocCount );
+
+    long nStartRow, nEndRow;
+    bool bFreezedLayouts = false;
+    // to collect temporary email files
+    ::std::vector< OUString> aFilesToRemove;
+
+    // The SfxObjectShell will be closed explicitly later but
+    // it is more safe to use SfxObjectShellLock here
+    SfxObjectShellLock xWorkDocSh;
+    SwView*            pWorkView             = nullptr;
+    SwDoc*             pWorkDoc              = nullptr;
+    SwDBManager*       pWorkDocOrigDBManager = nullptr;
+    SwWrtShell*        pWorkShell            = nullptr;
+    bool               bWorkDocInitialized   = false;
+
+    do
+    {
+        nStartRow = pImpl->pMergeData ? pImpl->pMergeData->xResultSet->getRow() : 0;
+
+        OUString sPath = rMergeDescriptor.sPath;
+        OUString sColumnData;
+
+        // Read the indicated data column, which should contain a valid mail
+        // address or an optional file name
+        if( bMT_EMAIL )
+        {
+            sColumnData = GetDBField( xColumnProp, aColumnDBFormat );
+            if( !SwMailMergeHelper::CheckMailAddress( sColumnData ) )
+            {
+                OSL_FAIL("invalid e-Mail address in database column");
+                nDocNo++;
+                ToNextMergeRecord(nWantedDBrecords);
+                nEndRow = pImpl->pMergeData ? pImpl->pMergeData->xResultSet->getRow() : 0;
+                continue;
+            }
+        }
+        else if( bColumnName )
+        {
+            sColumnData = GetDBField( xColumnProp, aColumnDBFormat );
+            if (sColumnData.isEmpty())
+                sColumnData = "_";
+            sPath += sColumnData;
+        }
+
+        // create a new temporary file name - only done once in case of bCreateSingleFile
+        if( bNeedsTempFiles && ( !bWorkDocInitialized || !bCreateSingleFile ))
+        {
+            INetURLObject aEntry(sPath);
+            OUString sLeading;
+            //#i97667# if the name is from a database field then it will be used _as is_
+            if( !sColumnData.isEmpty() )
+                sLeading = sColumnData;
+            else
+                sLeading = aEntry.GetBase();
+            aEntry.removeSegment();
+            sPath = aEntry.GetMainURL( INetURLObject::NO_DECODE );
+            OUString sExt(comphelper::string::stripStart(pStoreToFilter->GetDefaultExtension(), '*'));
+            aTempFile.reset( new utl::TempFile(sLeading, true, &sExt, &sPath) );
+            if( !aTempFile->IsValid() )
             {
-                // construct the process dialog
-                pSourceWindow = &pSourceShell->GetView().GetEditWin();
-                if( !pParent )
-                    pParent = pSourceWindow;
+                ErrorHandler::HandleError( ERRCODE_IO_NOTSUPPORTED );
+                m_aMergeStatus = MergeStatus::ERROR;
+            }
+        }
+
+        if( IsMergeOk() )
+        {
+            std::unique_ptr< INetURLObject > aTempFileURL;
+            if( bNeedsTempFiles )
+                aTempFileURL.reset( new INetURLObject(aTempFile->GetURL()));
+            if( !bIsMergeSilent ) {
                 if( !bMT_PRINTER )
-                    pProgressDlg = VclPtr<CreateMonitor>::Create(
-                        pParent, pParent != pSourceWindow );
+                    static_cast<CreateMonitor*>( pProgressDlg.get() )->SetCurrentPosition( nDocNo );
                 else {
-                    pProgressDlg = VclPtr<PrintMonitor>::Create(
-                        pParent, pParent != pSourceWindow,
-                        PrintMonitor::MONITOR_TYPE_PRINT );
-                    static_cast<PrintMonitor*>( pProgressDlg.get() )->SetText(
-                        pSourceDocSh->GetTitle(22) );
+                    PrintMonitor *pPrintMonDlg = static_cast<PrintMonitor*>( pProgressDlg.get() );
+                    pPrintMonDlg->m_pPrinter->SetText( bNeedsTempFiles
+                        ? aTempFileURL->GetBase() : pSourceDocSh->GetTitle( 22 ) );
+                    OUString sStat( SW_RES(STR_STATSTR_LETTER) );
+                    sStat += " " + OUString::number( nDocNo );
+                    pPrintMonDlg->m_pPrintInfo->SetText( sStat );
                 }
-                pProgressDlg->SetCancelHdl( LINK(this, SwDBManager, PrtCancelHdl) );
-                pProgressDlg->Show();
-
-                RESCHEDULE_GUI;
+                pProgressDlg->Update();
             }
 
-            if( bCreateSingleFile )
-            {
-                // create a target docshell to put the merged document into
-                xTargetDocShell = lcl_CreateWorkingDocument( WorkingDocType::TARGET,
-                    pSourceDocSh->GetDoc(), bMT_SHELL ? pSourceWindow : nullptr,
-                    nullptr, &pTargetView, &pTargetShell, &pTargetDoc );
-                if (nMaxDumpDocs)
-                    lcl_SaveDebugDoc( xTargetDocShell, "MergeDoc" );
+            RESCHEDULE_GUI;
 
-                // determine the page style and number used at the start of the source document
-                pSourceShell->SttEndDoc(true);
-                nStartingPageNo = pSourceShell->GetVirtPageNum();
+            // Create a copy of the source document and work with that one instead of the source.
+            // If we're not in the single file mode (which requires modifying the document for the merging),
+            // it is enough to do this just once. Currently PDF also has to be treated special.
+            if( !bWorkDocInitialized || bCreateSingleFile || bIsPDFeport )
+            {
+                assert( !xWorkDocSh.Is());
+                pWorkDocOrigDBManager = this;
+                xWorkDocSh = lcl_CreateWorkingDocument( WorkingDocType::COPY,
+                    pSourceDocSh->GetDoc(), nullptr, &pWorkDocOrigDBManager,
+                    &pWorkView, &pWorkShell, &pWorkDoc );
+                if ( (nMaxDumpDocs < 0) || (nDocNo <= nMaxDumpDocs) )
+                    lcl_SaveDebugDoc( xWorkDocSh, "WorkDoc", nDocNo );
+
+                // #i69458# lock fields to prevent access to the result set while calculating layout
+                // tdf#92324: and do not unlock: keep document locked during printing to avoid
+                // ExpFields update during printing, generation of preview, etc.
+                pWorkShell->LockExpFields();
+                pWorkShell->CalcLayout();
             }
 
-            // Progress, to prohibit KeyInputs
-            SfxProgress aProgress(pSourceDocSh, ::aEmptyOUStr, 1);
+            EMIT_SW_EVENT(FIELD_MERGE, xWorkDocSh);
 
-            // lock all dispatchers
-            SfxViewFrame* pViewFrame = SfxViewFrame::GetFirst(pSourceDocSh);
-            while (pViewFrame)
+            // tdf#92324: Allow ExpFields update only by explicit instruction to avoid
+            // database cursor movement on any other fields update, for example during
+            // print preview and other operations
+            if ( pWorkShell->IsExpFieldsLocked() )
+                pWorkShell->UnlockExpFields();
+            pWorkShell->SwViewShell::UpdateFields();
+            pWorkShell->LockExpFields();
+
+            EMIT_SW_EVENT(FIELD_MERGE_FINISHED, xWorkDocSh);
+
+            // also emit MailMergeEvent on XInterface if possible
+            const SwXMailMerge *pEvtSrc = GetMailMergeEvtSrc();
+            if(pEvtSrc)
             {
-                pViewFrame->GetDispatcher()->Lock(true);
-                pViewFrame = SfxViewFrame::GetNext(*pViewFrame, pSourceDocSh);
+                uno::Reference< uno::XInterface > xRef(
+                    static_cast<text::XMailMergeBroadcaster*>(const_cast<SwXMailMerge*>(pEvtSrc)) );
+                text::MailMergeEvent aEvt( xRef, xWorkDocSh->GetModel() );
+                pEvtSrc->LaunchMailMergeEvent( aEvt );
             }
 
-            sal_Int32 nDocNo = 1;
-            sal_Int32 nDocCount = 0;
-            // For single file mode, the number of pages in the target document so far, which is used
-            // by AppendDoc() to adjust position of page-bound objects. Getting this information directly
-            // from the target doc would require repeated layouts of the doc, which is expensive, but
-            // it can be manually computed from the source documents (for which we do layouts, so the page
-            // count is known, and there is a blank page between each of them in the target document).
-            int targetDocPageCount = 0;
-            if( !bIsMergeSilent && !bMT_PRINTER &&
-                    lcl_getCountFromResultSet( nDocCount, pImpl->pMergeData->xResultSet ) )
-                static_cast<CreateMonitor*>( pProgressDlg.get() )->SetTotalCount( nDocCount );
-
-            long nStartRow, nEndRow;
-            bool bFreezedLayouts = false;
-            // to collect temporary email files
-            ::std::vector< OUString> aFilesToRemove;
-
-            // The SfxObjectShell will be closed explicitly later but
-            // it is more safe to use SfxObjectShellLock here
-            SfxObjectShellLock xWorkDocSh;
-            SwView*            pWorkView             = nullptr;
-            SwDoc*             pWorkDoc              = nullptr;
-            SwDBManager*       pWorkDocOrigDBManager = nullptr;
-            SwWrtShell*        pWorkShell            = nullptr;
-            bool               bWorkDocInitialized   = false;
-
-            do
+            // working copy is merged - prepare final steps depending on merge options
+
+            if( bCreateSingleFile )
             {
-                nStartRow = pImpl->pMergeData ? pImpl->pMergeData->xResultSet->getRow() : 0;
+                assert( pTargetShell && "no target shell available!" );
+
+                // prepare working copy and target to append
+
+                pWorkDoc->RemoveInvisibleContent();
+                pWorkShell->ConvertFieldsToText();
+                pWorkShell->SetNumberingRestart();
+                if( bSynchronizedDoc )
                 {
-                    OUString sPath = rMergeDescriptor.sPath;
-                    OUString sColumnData;
+                    lcl_RemoveSectionLinks( *pWorkShell );
+                }
 
-                    // Read the indicated data column, which should contain a valid mail
-                    // address or an optional file name
-                    if( bMT_EMAIL )
-                    {
-                        sColumnData = GetDBField( xColumnProp, aColumnDBFormat );
-                        if( !SwMailMergeHelper::CheckMailAddress( sColumnData ) )
-                        {
-                            OSL_FAIL("invalid e-Mail address in database column");
-                            nDocNo++;
-                            ToNextMergeRecord(nWantedDBrecords);
-                            nEndRow = pImpl->pMergeData ? pImpl->pMergeData->xResultSet->getRow() : 0;
-                            continue;
-                        }
-                    }
-                    else if( bColumnName )
-                    {
-                        sColumnData = GetDBField( xColumnProp, aColumnDBFormat );
-                        if (sColumnData.isEmpty())
-                            sColumnData = "_";
-                        sPath += sColumnData;
-                    }
+                if ( (nMaxDumpDocs < 0) || (nDocNo <= nMaxDumpDocs) )
+                    lcl_SaveDebugDoc( xWorkDocSh, "WorkDoc", nDocNo );
 
-                    // create a new temporary file name - only done once in case of bCreateSingleFile
-                    if( bNeedsTempFiles && ( !bWorkDocInitialized || !bCreateSingleFile ))
-                    {
-                        INetURLObject aEntry(sPath);
-                        OUString sLeading;
-                        //#i97667# if the name is from a database field then it will be used _as is_
-                        if( !sColumnData.isEmpty() )
-                            sLeading = sColumnData;
-                        else
-                            sLeading = aEntry.GetBase();
-                        aEntry.removeSegment();
-                        sPath = aEntry.GetMainURL( INetURLObject::NO_DECODE );
-                        OUString sExt(comphelper::string::stripStart(pStoreToFilter->GetDefaultExtension(), '*'));
-                        aTempFile.reset(
-                            new utl::TempFile(sLeading, true, &sExt, &sPath));
-                        if( !aTempFile->IsValid() )
-                        {
-                            ErrorHandler::HandleError( ERRCODE_IO_NOTSUPPORTED );
-                            m_aMergeStatus = MergeStatus::ERROR;
-                        }
-                    }
+                // append the working document to the target document
+                if( targetDocPageCount % 2 == 1 )
+                    ++targetDocPageCount; // Docs always start on odd pages (so offset must be even).
+                SwNodeIndex appendedDocStart = pTargetDoc->AppendDoc( *pWorkDoc,
+                    nStartingPageNo, !bWorkDocInitialized, targetDocPageCount, nDocNo);
+                targetDocPageCount += pWorkShell->GetPageCnt();
 
-                    if( IsMergeOk() )
-                    {
-                        std::unique_ptr< INetURLObject > aTempFileURL;
-                        if( bNeedsTempFiles )
-                            aTempFileURL.reset( new INetURLObject(aTempFile->GetURL()));
-                        if( !bIsMergeSilent ) {
-                            if( !bMT_PRINTER )
-                                static_cast<CreateMonitor*>( pProgressDlg.get() )->SetCurrentPosition( nDocNo );
-                            else {
-                                PrintMonitor *pPrintMonDlg = static_cast<PrintMonitor*>( pProgressDlg.get() );
-                                pPrintMonDlg->m_pPrinter->SetText( bNeedsTempFiles ? aTempFileURL->GetBase() : OUString( pSourceDocSh->GetTitle( 22 )));
-                                OUString sStat(SW_RES(STR_STATSTR_LETTER));
-                                sStat += " ";
-                                sStat += OUString::number( nDocNo );
-                                pPrintMonDlg->m_pPrintInfo->SetText( sStat );
-                            }
-                            pProgressDlg->Update();
-                        }
-
-                        RESCHEDULE_GUI;
-
-                        // Create a copy of the source document and work with that one instead of the source.
-                        // If we're not in the single file mode (which requires modifying the document for the merging),
-                        // it is enough to do this just once. Currently PDF also has to be treated special.
-                        if( !bWorkDocInitialized || bCreateSingleFile || bIsPDFeport )
-                        {
-                            assert( !xWorkDocSh.Is());
-                            pWorkDocOrigDBManager = this;
-                            xWorkDocSh = lcl_CreateWorkingDocument( WorkingDocType::COPY,
-                                pSourceDocSh->GetDoc(), nullptr, &pWorkDocOrigDBManager,
-                                &pWorkView, &pWorkShell, &pWorkDoc );
-                            if ( (nMaxDumpDocs < 0) || (nDocNo <= nMaxDumpDocs) )
-                                lcl_SaveDebugDoc( xWorkDocSh, "WorkDoc", nDocNo );
-
-                            // #i69458# lock fields to prevent access to the result set while calculating layout
-                            // tdf#92324: and do not unlock: keep document locked during printing to avoid
-                            // ExpFields update during printing, generation of preview, etc.
-                            pWorkShell->LockExpFields();
-                            pWorkShell->CalcLayout();
-                        }
-
-                        EMIT_SW_EVENT(FIELD_MERGE, xWorkDocSh);
-
-                        // tdf#92324: Allow ExpFields update only by explicit instruction to avoid
-                        // database cursor movement on any other fields update, for example during
-                        // print preview and other operations
-                        if ( pWorkShell->IsExpFieldsLocked() )
-                            pWorkShell->UnlockExpFields();
-                        pWorkShell->SwViewShell::UpdateFields();
-                        pWorkShell->LockExpFields();
-
-                        EMIT_SW_EVENT(FIELD_MERGE_FINISHED, xWorkDocSh);
-
-                        // also emit MailMergeEvent on XInterface if possible
-                        const SwXMailMerge *pEvtSrc = GetMailMergeEvtSrc();
-                        if(pEvtSrc)
-                        {
-                            uno::Reference< uno::XInterface > xRef(
-                                static_cast<text::XMailMergeBroadcaster*>(const_cast<SwXMailMerge*>(pEvtSrc)) );
-                            text::MailMergeEvent aEvt( xRef, xWorkDocSh->GetModel() );
-                            pEvtSrc->LaunchMailMergeEvent( aEvt );
-                        }
-
-                        // working copy is merged - prepare final steps depending on merge options
-
-                        if( bCreateSingleFile )
-                        {
-                            assert( pTargetShell && "no target shell available!" );
-
-                            // prepare working copy and target to append
-
-                            pWorkDoc->RemoveInvisibleContent();
-                            pWorkShell->ConvertFieldsToText();
-                            pWorkShell->SetNumberingRestart();
-                            if( bSynchronizedDoc )
-                            {
-                                lcl_RemoveSectionLinks( *pWorkShell );
-                            }
-
-                            if ( (nMaxDumpDocs < 0) || (nDocNo <= nMaxDumpDocs) )
-                                lcl_SaveDebugDoc( xWorkDocSh, "WorkDoc", nDocNo );
-
-                            // append the working document to the target document
-                            if( targetDocPageCount % 2 == 1 )
-                                ++targetDocPageCount; // Docs always start on odd pages (so offset must be even).
-                            SwNodeIndex appendedDocStart = pTargetDoc->AppendDoc( *pWorkDoc,
-                                nStartingPageNo, !bWorkDocInitialized, targetDocPageCount, nDocNo);
-                            targetDocPageCount += pWorkShell->GetPageCnt();
-
-                            if ( (nMaxDumpDocs < 0) || (nDocNo <= nMaxDumpDocs) )
-                                lcl_SaveDebugDoc( xTargetDocShell, "MergeDoc" );
-
-                            if (bMT_SHELL)
-                            {
-                                SwDocMergeInfo aMergeInfo;
-                                // Name of the mark is actually irrelevant, UNO bookmarks have internals names.
-                                aMergeInfo.startPageInTarget = pTargetDoc->getIDocumentMarkAccess()->makeMark( appendedDocStart, "",
-                                    IDocumentMarkAccess::MarkType::UNO_BOOKMARK );
-                                aMergeInfo.nDBRow = nStartRow;
-                                rMergeDescriptor.pMailMergeConfigItem->AddMergedDocument( aMergeInfo );
-                            }
-                        }
-                        else if( bMT_PRINTER )
-                        {
-                            if( !bWorkDocInitialized ) // set up printing only once at the beginning
-                            {
-                                uno::Sequence< beans::PropertyValue > aOptions( rMergeDescriptor.aPrintOptions );
-                                lcl_PreparePrinterOptions( rMergeDescriptor.aPrintOptions, false, aOptions );
-
-                                pWorkView->StartPrint( aOptions, bIsMergeSilent, rMergeDescriptor.bPrintAsync );
-                                // some GetPrinter functions have a true default, so keep the false
-                                SfxPrinter* pDocPrt = pWorkView->GetPrinter( false );
-                                JobSetup aJobSetup = pDocPrt ? pDocPrt->GetJobSetup() : pWorkView->GetJobSetup();
-                                if( !Printer::PreparePrintJob( pWorkView->GetPrinterController(), aJobSetup ) )
-                                    MergeCancel();
-                            }
-                            if( IsMergeOk() && !Printer::ExecutePrintJob( pWorkView->GetPrinterController()) )
-                            {
-                                m_aMergeStatus = MergeStatus::ERROR;
-                            }
-                        }
-                        else
-                        {
-                            assert( bNeedsTempFiles );
-                            assert( pWorkShell->IsExpFieldsLocked() );
-
-                            // fields are locked, so it's fine to
-                            // restore the old / empty DB manager for save
-                            pWorkDoc->SetDBManager( pWorkDocOrigDBManager );
-
-                            // save merged document
-                            OUString sFileURL;
-                            if( !lcl_SaveDoc( aTempFileURL.get(), pStoreToFilter, pStoreToFilterOptions,
-                                              &rMergeDescriptor.aSaveToFilterData, bIsPDFeport,
-                                              xWorkDocSh, *pWorkShell, &sFileURL ) )
-                            {
-                                m_aMergeStatus = MergeStatus::ERROR;
-                            }
-
-                            // back to the MM DB manager
-                            pWorkDoc->SetDBManager( this );
-
-                            if( bMT_EMAIL && !IsMergeError() )
-                            {
-                                // schedule file for later removal
-                                aFilesToRemove.push_back( sFileURL );
-
-                                uno::Reference< mail::XMailMessage > xMessage = lcl_CreateMailFromDoc(
-                                    rMergeDescriptor, sFileURL, sColumnData, sMailBodyMimeType,
-                                    sMailEncoding, pStoreToFilter->GetMimeType() );
-                                if( xMessage.is() )
-                                {
-                                    xMailDispatcher->enqueueMailMessage( xMessage );
-                                    if( !xMailDispatcher->isStarted() )
-                                        xMailDispatcher->start();
-                                }
-                            }
-                        }
-                        if( bCreateSingleFile || bIsPDFeport )
-                        {
-                            pWorkDoc->SetDBManager( pWorkDocOrigDBManager );
-                            xWorkDocSh->DoClose();
-                            xWorkDocSh = nullptr;
-                        }
-                    }
-                }
-                bWorkDocInitialized = true;
-                nDocNo++;
-                nEndRow = pImpl->pMergeData ? pImpl->pMergeData->xResultSet->getRow() : 0;
+                if ( (nMaxDumpDocs < 0) || (nDocNo <= nMaxDumpDocs) )
+                    lcl_SaveDebugDoc( xTargetDocShell, "MergeDoc" );
 
-                // Freeze the layouts of the target document after the first inserted
-                // sub-document, to get the correct PageDesc.
-                if(!bFreezedLayouts && bCreateSingleFile)
+                if (bMT_SHELL)
                 {
-                    for ( auto aLayout : pTargetShell->GetDoc()->GetAllLayouts() )
-                        aLayout->FreezeLayout(true);
-                    bFreezedLayouts = true;
+                    SwDocMergeInfo aMergeInfo;
+                    // Name of the mark is actually irrelevant, UNO bookmarks have internals names.
+                    aMergeInfo.startPageInTarget = pTargetDoc->getIDocumentMarkAccess()->makeMark(
+                        appendedDocStart, "", IDocumentMarkAccess::MarkType::UNO_BOOKMARK );
+                    aMergeInfo.nDBRow = nStartRow;
+                    rMergeDescriptor.pMailMergeConfigItem->AddMergedDocument( aMergeInfo );
                 }
-            } while( IsMergeOk() &&
-                ((bSynchronizedDoc && (nStartRow != nEndRow)) ? IsValidMergeRecord() : ToNextMergeRecord()));
-
-            if ( xWorkDocSh.Is() && pWorkView->GetWrtShell().IsExpFieldsLocked() )
-            {
-                // Unlock document fields after merge complete
-                pWorkView->GetWrtShell().UnlockExpFields();
             }
-
-            if( !bCreateSingleFile )
+            else if( bMT_PRINTER )
             {
-                if( bMT_PRINTER )
-                    Printer::FinishPrintJob( pWorkView->GetPrinterController());
-                if( !bIsPDFeport )
+                if( !bWorkDocInitialized ) // set up printing only once at the beginning
                 {
-                    pWorkDoc->SetDBManager( pWorkDocOrigDBManager );
-                    xWorkDocSh->DoClose();
+                    uno::Sequence< beans::PropertyValue > aOptions( rMergeDescriptor.aPrintOptions );
+                    lcl_PreparePrinterOptions( rMergeDescriptor.aPrintOptions, false, aOptions );
+
+                    pWorkView->StartPrint( aOptions, bIsMergeSilent, rMergeDescriptor.bPrintAsync );
+                    // some GetPrinter functions have a true default, so keep the false
+                    SfxPrinter* pDocPrt = pWorkView->GetPrinter( false );
+                    JobSetup aJobSetup = pDocPrt ? pDocPrt->GetJobSetup() : pWorkView->GetJobSetup();
+                    if( !Printer::PreparePrintJob( pWorkView->GetPrinterController(), aJobSetup ) )
+                        MergeCancel();
+                }
+                if( IsMergeOk() && !Printer::ExecutePrintJob( pWorkView->GetPrinterController()) )
+                {
+                    m_aMergeStatus = MergeStatus::ERROR;
                 }
             }
-            else if( IsMergeOk() ) // && bCreateSingleFile
+            else
             {
-                RESCHEDULE_GUI;
-
-                // sw::DocumentLayoutManager::CopyLayoutFormat() did not generate
-                // unique fly names, do it here once.
-                pTargetDoc->SetInMailMerge(false);
-                pTargetDoc->SetAllUniqueFlyNames();
-
-                // Unfreeze target document layouts and correct all PageDescs.
-                pTargetShell->CalcLayout();
-                for ( auto aLayout : pTargetShell->GetDoc()->GetAllLayouts() )
+                assert( bNeedsTempFiles );
+                assert( pWorkShell->IsExpFieldsLocked() );
+
+                // fields are locked, so it's fine to
+                // restore the old / empty DB manager for save
+                pWorkDoc->SetDBManager( pWorkDocOrigDBManager );
+
+                // save merged document
+                OUString sFileURL;
+                if( !lcl_SaveDoc( aTempFileURL.get(), pStoreToFilter, pStoreToFilterOptions,
+                                  &rMergeDescriptor.aSaveToFilterData, bIsPDFeport,
+                                  xWorkDocSh, *pWorkShell, &sFileURL ) )
                 {
-                    aLayout->FreezeLayout(false);
-                    aLayout->AllCheckPageDescs();
+                    m_aMergeStatus = MergeStatus::ERROR;
                 }
 
-                RESCHEDULE_GUI;
+                // back to the MM DB manager
+                pWorkDoc->SetDBManager( this );
 
-                if( IsMergeOk() && bMT_FILE )
+                if( bMT_EMAIL && !IsMergeError() )
                 {
-                    // save merged document
-                    assert( aTempFile.get() );
-                    INetURLObject aTempFileURL( !rMergeDescriptor.sPath.isEmpty() ?
-                                                 rMergeDescriptor.sPath : aTempFile->GetURL() );
-                    if( !lcl_SaveDoc( &aTempFileURL, pStoreToFilter,
-                            pStoreToFilterOptions, &rMergeDescriptor.aSaveToFilterData,
-                            bIsPDFeport, xTargetDocShell, *pTargetShell ) )
+                    // schedule file for later removal
+                    aFilesToRemove.push_back( sFileURL );
+
+                    uno::Reference< mail::XMailMessage > xMessage = lcl_CreateMailFromDoc(
+                        rMergeDescriptor, sFileURL, sColumnData, sMailBodyMimeType,
+                        sMailEncoding, pStoreToFilter->GetMimeType() );
+                    if( xMessage.is() )
                     {
-                        m_aMergeStatus = MergeStatus::ERROR;
+                        xMailDispatcher->enqueueMailMessage( xMessage );
+                        if( !xMailDispatcher->isStarted() )
+                            xMailDispatcher->start();
                     }
                 }
-                else if( IsMergeOk() && bMT_PRINTER )
-                {
-                    // print the target document
-                    uno::Sequence< beans::PropertyValue > aOptions( rMergeDescriptor.aPrintOptions );
-                    lcl_PreparePrinterOptions( rMergeDescriptor.aPrintOptions, true, aOptions );
-                    pTargetView->ExecPrint( aOptions, bIsMergeSilent, rMergeDescriptor.bPrintAsync );
-                }
-
-                if( IsMergeOk() && bMT_SHELL )
-                    // leave docshell available for caller (e.g. MM wizard)
-                    rMergeDescriptor.pMailMergeConfigItem->SetTargetView( pTargetView );
-                else
-                    xTargetDocShell->DoClose();
             }
+            if( bCreateSingleFile || bIsPDFeport )
+            {
+                pWorkDoc->SetDBManager( pWorkDocOrigDBManager );
+                xWorkDocSh->DoClose();
+                xWorkDocSh = nullptr;
+            }
+        }
+
+        bWorkDocInitialized = true;
+        nDocNo++;
+        nEndRow = pImpl->pMergeData ? pImpl->pMergeData->xResultSet->getRow() : 0;
+
+        // Freeze the layouts of the target document after the first inserted
+        // sub-document, to get the correct PageDesc.
+        if(!bFreezedLayouts && bCreateSingleFile)
+        {
+            for ( auto aLayout : pTargetShell->GetDoc()->GetAllLayouts() )
+                aLayout->FreezeLayout(true);
+            bFreezedLayouts = true;
+        }
+    } while( IsMergeOk() &&
+        ((bSynchronizedDoc && (nStartRow != nEndRow)) ? IsValidMergeRecord() : ToNextMergeRecord()));
+
+    if ( xWorkDocSh.Is() && pWorkView->GetWrtShell().IsExpFieldsLocked() )
+    {
+        // Unlock document fields after merge complete
+        pWorkView->GetWrtShell().UnlockExpFields();
+    }
+
+    if( !bCreateSingleFile )
+    {
+        if( bMT_PRINTER )
+            Printer::FinishPrintJob( pWorkView->GetPrinterController());
+        if( !bIsPDFeport )
+        {
+            pWorkDoc->SetDBManager( pWorkDocOrigDBManager );
+            xWorkDocSh->DoClose();
+        }
+    }
+    else if( IsMergeOk() ) // && bCreateSingleFile
+    {
+        RESCHEDULE_GUI;
 
-            pProgressDlg.disposeAndClear();
+        // sw::DocumentLayoutManager::CopyLayoutFormat() did not generate
+        // unique fly names, do it here once.
+        pTargetDoc->SetInMailMerge(false);
+        pTargetDoc->SetAllUniqueFlyNames();
 
-            // remove the temporary files
-            ::std::vector<OUString>::iterator aFileIter;
-            for(aFileIter = aFilesToRemove.begin();
-                        aFileIter != aFilesToRemove.end(); ++aFileIter)
-                SWUnoHelper::UCB_DeleteFile( *aFileIter );
+        // Unfreeze target document layouts and correct all PageDescs.
+        pTargetShell->CalcLayout();
+        for ( auto aLayout : pTargetShell->GetDoc()->GetAllLayouts() )
+        {
+            aLayout->FreezeLayout(false);
+            aLayout->AllCheckPageDescs();
+        }
 
-            // unlock all dispatchers
-            pViewFrame = SfxViewFrame::GetFirst(pSourceDocSh);
-            while (pViewFrame)
+        RESCHEDULE_GUI;
+
+        if( IsMergeOk() && bMT_FILE )
+        {
+            // save merged document
+            assert( aTempFile.get() );
+            INetURLObject aTempFileURL( !rMergeDescriptor.sPath.isEmpty() ?
+                                         rMergeDescriptor.sPath : aTempFile->GetURL() );
+            if( !lcl_SaveDoc( &aTempFileURL, pStoreToFilter,
+                    pStoreToFilterOptions, &rMergeDescriptor.aSaveToFilterData,
+                    bIsPDFeport, xTargetDocShell, *pTargetShell ) )
             {
-                pViewFrame->GetDispatcher()->Lock(false);
-                pViewFrame = SfxViewFrame::GetNext(*pViewFrame, pSourceDocSh);
+                m_aMergeStatus = MergeStatus::ERROR;
             }
-
-            SW_MOD()->SetView(&pSourceShell->GetView());
         }
+        else if( IsMergeOk() && bMT_PRINTER )
+        {
+            // print the target document
+            uno::Sequence< beans::PropertyValue > aOptions( rMergeDescriptor.aPrintOptions );
+            lcl_PreparePrinterOptions( rMergeDescriptor.aPrintOptions, true, aOptions );
+            pTargetView->ExecPrint( aOptions, bIsMergeSilent, rMergeDescriptor.bPrintAsync );
+        }
+
+        if( IsMergeOk() && bMT_SHELL )
+            // leave docshell available for caller (e.g. MM wizard)
+            rMergeDescriptor.pMailMergeConfigItem->SetTargetView( pTargetView );
+        else
+            xTargetDocShell->DoClose();
     }
 
+    RESCHEDULE_GUI;
+
+    pProgressDlg.disposeAndClear();
+
+    // remove the temporary files
+    for( const OUString &sFileURL : aFilesToRemove )
+        SWUnoHelper::UCB_DeleteFile( sFileURL );
+
+    // unlock all dispatchers
+    pViewFrame = SfxViewFrame::GetFirst(pSourceDocSh);
+    while (pViewFrame)
+    {
+        pViewFrame->GetDispatcher()->Lock(false);
+        pViewFrame = SfxViewFrame::GetNext(*pViewFrame, pSourceDocSh);
+    }
+
+    SW_MOD()->SetView(&pSourceShell->GetView());
+
     if( xMailDispatcher.is() )
     {
         xMailDispatcher->stop();
@@ -2841,26 +2837,22 @@ void SwDBManager::ExecuteFormLetter( SwWrtShell& rSh,
         SfxObjectShellRef xDocShell = rSh.GetView().GetViewFrame()->GetObjectShell();
 
         EMIT_SW_EVENT(MAIL_MERGE, xDocShell);
-        {
-            {
-                {
-                    // prepare mail merge descriptor
-                    SwMergeDescriptor aMergeDesc( pImpl->pMergeDialog->GetMergeType(), rSh, aDescriptor );
-                    aMergeDesc.sSaveToFilter = pImpl->pMergeDialog->GetSaveFilter();
-                    aMergeDesc.bCreateSingleFile = pImpl->pMergeDialog->IsSaveSingleDoc();
-                    aMergeDesc.sPath = INetURLObject::TryUrlFromSystemPathAsString(
-                        pImpl->pMergeDialog->GetPath( true ) );
-                    if( !aMergeDesc.sPath.isEmpty() && !aMergeDesc.sPath.endsWith("/") )
-                        aMergeDesc.sPath += "/";
-                    if( !aMergeDesc.bCreateSingleFile && pImpl->pMergeDialog->IsGenerateFromDataBase() )
-                    {
-                        aMergeDesc.sDBcolumn = pImpl->pMergeDialog->GetColumnName();
-                    }
 
-                    Merge( aMergeDesc );
-                }
-            }
+        // prepare mail merge descriptor
+        SwMergeDescriptor aMergeDesc( pImpl->pMergeDialog->GetMergeType(), rSh, aDescriptor );
+        aMergeDesc.sSaveToFilter = pImpl->pMergeDialog->GetSaveFilter();
+        aMergeDesc.bCreateSingleFile = pImpl->pMergeDialog->IsSaveSingleDoc();
+        aMergeDesc.sPath = INetURLObject::TryUrlFromSystemPathAsString(
+            pImpl->pMergeDialog->GetPath( true ) );
+        if( !aMergeDesc.sPath.isEmpty() && !aMergeDesc.sPath.endsWith("/") )
+            aMergeDesc.sPath += "/";
+        if( !aMergeDesc.bCreateSingleFile && pImpl->pMergeDialog->IsGenerateFromDataBase() )
+        {
+            aMergeDesc.sDBcolumn = pImpl->pMergeDialog->GetColumnName();
         }
+
+        Merge( aMergeDesc );
+
         EMIT_SW_EVENT(MAIL_MERGE_END, xDocShell);
 
         // reset the cursor inside
commit f1ac16d2e13b021a9c368fb321d0e81218d0c77e
Author: Jan-Marek Glogowski <glogow at fbihome.de>
Date:   Wed Jan 27 13:59:42 2016 +0100

    MM: rename MergeNew => Merge
    
    Since all old code from the original Merge function is gone, just
    do the rename.
    
    Change-Id: I7cc1b4b58cc73bea83a723b2478a8b4bf59a382f

diff --git a/sw/inc/dbmgr.hxx b/sw/inc/dbmgr.hxx
index 36f12b3..1fde6ec 100644
--- a/sw/inc/dbmgr.hxx
+++ b/sw/inc/dbmgr.hxx
@@ -289,7 +289,7 @@ public:
     inline void     SetMergeSilent( bool bVal )     { bMergeSilent = bVal; }
 
     /// Merging of data records into fields.
-    bool            MergeNew( const SwMergeDescriptor& rMergeDesc, vcl::Window* pParent = nullptr );
+    bool            Merge( const SwMergeDescriptor& rMergeDesc, vcl::Window* pParent = nullptr );
     void            MergeCancel();
 
     inline bool     IsMergeOk()     { return MergeStatus::OK     == m_aMergeStatus; };
diff --git a/sw/source/ui/dbui/mailmergewizard.cxx b/sw/source/ui/dbui/mailmergewizard.cxx
index 41b504b..22b55f9 100644
--- a/sw/source/ui/dbui/mailmergewizard.cxx
+++ b/sw/source/ui/dbui/mailmergewizard.cxx
@@ -283,7 +283,7 @@ void SwMailMergeWizard::CreateTargetDocument()
     aMergeDesc.pMailMergeConfigItem = &m_rConfigItem;
     aMergeDesc.bCreateSingleFile = true;
 
-    GetSwView()->GetWrtShell().GetDBManager()->MergeNew( aMergeDesc, this );
+    GetSwView()->GetWrtShell().GetDBManager()->Merge( aMergeDesc, this );
     m_rConfigItem.SetMergeDone();
     if( m_rConfigItem.GetTargetView() )
         m_rConfigItem.GetTargetView()->GetViewFrame()->GetFrame().Appear();
diff --git a/sw/source/ui/dbui/mmpreparemergepage.cxx b/sw/source/ui/dbui/mmpreparemergepage.cxx
index 662f94f..d2025d5 100644
--- a/sw/source/ui/dbui/mmpreparemergepage.cxx
+++ b/sw/source/ui/dbui/mmpreparemergepage.cxx
@@ -139,7 +139,7 @@ void SwMailMergePrepareMergePage:: MoveHdl_Impl(Control* pCtrl)
 
     SwWrtShell& rSh = m_pWizard->GetSwView()->GetWrtShell();
     SwMergeDescriptor aMergeDesc( DBMGR_MERGE, rSh, aDescriptor );
-    rSh.GetDBManager()->MergeNew(aMergeDesc);
+    rSh.GetDBManager()->Merge(aMergeDesc);
 }
 
 IMPL_LINK_TYPED( SwMailMergePrepareMergePage, ExcludeHdl_Impl, Button*, pBox, void)
diff --git a/sw/source/uibase/dbui/dbmgr.cxx b/sw/source/uibase/dbui/dbmgr.cxx
index 1eaac6d..57c68b1 100644
--- a/sw/source/uibase/dbui/dbmgr.cxx
+++ b/sw/source/uibase/dbui/dbmgr.cxx
@@ -421,7 +421,7 @@ static bool lcl_GetColumnCnt(SwDSParam* pParam, const OUString& rColumnName,
 };
 
 // import data
-bool SwDBManager::MergeNew( const SwMergeDescriptor& rMergeDesc, vcl::Window* pParent )
+bool SwDBManager::Merge( const SwMergeDescriptor& rMergeDesc, vcl::Window* pParent )
 {
     assert( !bInMerge && !pImpl->pMergeData && "merge already activated!" );
 
@@ -2857,7 +2857,7 @@ void SwDBManager::ExecuteFormLetter( SwWrtShell& rSh,
                         aMergeDesc.sDBcolumn = pImpl->pMergeDialog->GetColumnName();
                     }
 
-                    MergeNew( aMergeDesc );
+                    Merge( aMergeDesc );
                 }
             }
         }
diff --git a/sw/source/uibase/shells/textsh2.cxx b/sw/source/uibase/shells/textsh2.cxx
index 6d2ccb2..33f2b87 100644
--- a/sw/source/uibase/shells/textsh2.cxx
+++ b/sw/source/uibase/shells/textsh2.cxx
@@ -178,7 +178,7 @@ void SwTextShell::ExecDB(SfxRequest &rReq)
                 aDescriptor[daCommandType]  <<= nCommandTypeArg;
 
                 SwMergeDescriptor aMergeDesc( DBMGR_MERGE, *GetShellPtr(), aDescriptor );
-                pDBManager->MergeNew(aMergeDesc);
+                pDBManager->Merge(aMergeDesc);
 
                 if ( bDisposeResultSet )
                     ::comphelper::disposeComponent(xCursor);
diff --git a/sw/source/uibase/uno/unodispatch.cxx b/sw/source/uibase/uno/unodispatch.cxx
index 534aea5..ee9ac7c 100644
--- a/sw/source/uibase/uno/unodispatch.cxx
+++ b/sw/source/uibase/uno/unodispatch.cxx
@@ -219,7 +219,7 @@ void SwXDispatch::dispatch(const util::URL& aURL,
     {
         svx::ODataAccessDescriptor aDescriptor(aArgs);
         SwMergeDescriptor aMergeDesc( DBMGR_MERGE, rSh, aDescriptor );
-        pDBManager->MergeNew(aMergeDesc);
+        pDBManager->Merge(aMergeDesc);
     }
     else if(aURL.Complete.equalsAscii(cURLInsertColumns))
     {
diff --git a/sw/source/uibase/uno/unomailmerge.cxx b/sw/source/uibase/uno/unomailmerge.cxx
index f06d804..c8ec5a9 100644
--- a/sw/source/uibase/uno/unomailmerge.cxx
+++ b/sw/source/uibase/uno/unomailmerge.cxx
@@ -547,7 +547,7 @@ uno::Any SAL_CALL SwXMailMerge::execute(
             throw IllegalArgumentException("Property type mismatch or property not set: " + rName, static_cast < cppu::OWeakObject * > ( this ), 0 );
     }
 
-    // need to translate the selection: the API here requires a sequence of bookmarks, but the MergeNew
+    // need to translate the selection: the API here requires a sequence of bookmarks, but the Merge
     // method we will call below requires a sequence of indicies.
     if ( aCurSelection.getLength() )
     {
@@ -800,7 +800,7 @@ uno::Any SAL_CALL SwXMailMerge::execute(
     pMgr->SetMailMergeEvtSrc( this );   // launch events for listeners
 
     SfxGetpApp()->NotifyEvent(SfxEventHint(SW_EVENT_MAIL_MERGE, SwDocShell::GetEventName(STR_SW_EVENT_MAIL_MERGE), xCurDocSh));
-    bool bSucc = pMgr->MergeNew( aMergeDesc );
+    bool bSucc = pMgr->Merge( aMergeDesc );
     SfxGetpApp()->NotifyEvent(SfxEventHint(SW_EVENT_MAIL_MERGE_END, SwDocShell::GetEventName(STR_SW_EVENT_MAIL_MERGE_END), xCurDocSh));
 
     pMgr->SetMailMergeEvtSrc( pOldSrc );
commit e0a6ffbe51f04b50567ccba9d59d9e305c9620c4
Author: Jan-Marek Glogowski <glogow at fbihome.de>
Date:   Wed Jan 27 13:04:04 2016 +0100

    MM: don't try to save the source MM document
    
    Just create in internal copy, if the source document is modified.
    
    Change-Id: I4587b3df5ff0b42c98f1b69fe18b4f11f5c9b8e4

diff --git a/sw/source/uibase/dbui/dbmgr.cxx b/sw/source/uibase/dbui/dbmgr.cxx
index 1159f3f..1eaac6d 100644
--- a/sw/source/uibase/dbui/dbmgr.cxx
+++ b/sw/source/uibase/dbui/dbmgr.cxx
@@ -169,6 +169,13 @@ enum class SwDBNextRecord { NEXT, FIRST };
 static bool lcl_ToNextRecord( SwDSParam* pParam, const sal_uInt16 nSkip = 0,
                               const SwDBNextRecord action = SwDBNextRecord::NEXT );
 
+enum class WorkingDocType { SOURCE, TARGET, COPY };
+static SfxObjectShell* lcl_CreateWorkingDocument(
+    const WorkingDocType aType, const SwDoc* pSourceDoc,
+    const vcl::Window *pSourceWindow,
+    SwDBManager** const pDBManager,
+    SwView** const pView, SwWrtShell** const pWrtShell, SwDoc** const pDoc );
+
 static bool lcl_getCountFromResultSet( sal_Int32& rCount, const uno::Reference<sdbc::XResultSet>& xResultSet )
 {
     uno::Reference<beans::XPropertySet> xPrSet(xResultSet, uno::UNO_QUERY);
@@ -418,6 +425,35 @@ bool SwDBManager::MergeNew( const SwMergeDescriptor& rMergeDesc, vcl::Window* pP
 {
     assert( !bInMerge && !pImpl->pMergeData && "merge already activated!" );
 
+    SfxObjectShellLock  xWorkObjSh;
+    SwWrtShell         *pWorkShell;
+    SwDoc              *pWorkDoc;
+    SwDBManager        *pWorkDocOrigDBManager;
+
+    switch( rMergeDesc.nMergeType )
+    {
+        case DBMGR_MERGE_PRINTER:
+        case DBMGR_MERGE_EMAIL:
+        case DBMGR_MERGE_FILE:
+        case DBMGR_MERGE_SHELL:
+        {
+            SwDocShell *pSourceDocSh = rMergeDesc.rSh.GetView().GetDocShell();
+            if( pSourceDocSh->IsModified() )
+            {
+                pWorkDocOrigDBManager = this;
+                xWorkObjSh = lcl_CreateWorkingDocument(
+                    WorkingDocType::SOURCE, rMergeDesc.rSh.GetDoc(), nullptr,
+                    &pWorkDocOrigDBManager, nullptr, &pWorkShell, &pWorkDoc );
+            }
+            // fall through
+        }
+
+        default:
+            if( !xWorkObjSh.Is() )
+                pWorkShell = &rMergeDesc.rSh;
+            break;
+    }
+
     SwDBData aData;
     aData.nCommandType = sdb::CommandType::TABLE;
     uno::Reference<sdbc::XResultSet>  xResSet;
@@ -479,7 +515,7 @@ bool SwDBManager::MergeNew( const SwMergeDescriptor& rMergeDesc, vcl::Window* pP
 
     lcl_InitNumberFormatter(*pImpl->pMergeData, xSource);
 
-    rMergeDesc.rSh.ChgDBData(aData);
+    pWorkShell->ChgDBData(aData);
     bInMerge = true;
 
     if (IsInitDBFields())
@@ -487,13 +523,13 @@ bool SwDBManager::MergeNew( const SwMergeDescriptor& rMergeDesc, vcl::Window* pP
         // with database fields without DB-Name, use DB-Name from Doc
         std::vector<OUString> aDBNames;
         aDBNames.push_back(OUString());
-        SwDBData aInsertData = rMergeDesc.rSh.GetDBData();
+        SwDBData aInsertData = pWorkShell->GetDBData();
         OUString sDBName = aInsertData.sDataSource;
         sDBName += OUString(DB_DELIM);
         sDBName += aInsertData.sCommand;
         sDBName += OUString(DB_DELIM);
         sDBName += OUString::number(aInsertData.nCommandType);
-        rMergeDesc.rSh.ChangeDBFields( aDBNames, sDBName);
+        pWorkShell->ChangeDBFields( aDBNames, sDBName);
         SetInitDBFields(false);
     }
 
@@ -501,10 +537,10 @@ bool SwDBManager::MergeNew( const SwMergeDescriptor& rMergeDesc, vcl::Window* pP
     switch(rMergeDesc.nMergeType)
     {
         case DBMGR_MERGE:
-            rMergeDesc.rSh.StartAllAction();
-            rMergeDesc.rSh.SwViewShell::UpdateFields( true );
-            rMergeDesc.rSh.SetModified();
-            rMergeDesc.rSh.EndAllAction();
+            pWorkShell->StartAllAction();
+            pWorkShell->SwViewShell::UpdateFields( true );
+            pWorkShell->SetModified();
+            pWorkShell->EndAllAction();
             break;
 
         case DBMGR_MERGE_PRINTER:
@@ -512,18 +548,24 @@ bool SwDBManager::MergeNew( const SwMergeDescriptor& rMergeDesc, vcl::Window* pP
         case DBMGR_MERGE_FILE:
         case DBMGR_MERGE_SHELL:
             // save files and send them as e-Mail if required
-            bRet = MergeMailFiles(&rMergeDesc.rSh, rMergeDesc, pParent);
+            bRet = MergeMailFiles(pWorkShell, rMergeDesc, pParent);
             break;
 
         default:
             // insert selected entries
             // (was: InsertRecord)
-            ImportFromConnection(&rMergeDesc.rSh);
+            ImportFromConnection(pWorkShell);
             break;
     }
 
     DELETEZ( pImpl->pMergeData );
 
+    if( xWorkObjSh.Is() )
+    {
+        pWorkDoc->SetDBManager( pWorkDocOrigDBManager );
+        xWorkObjSh->DoClose();
+    }
+
     bInMerge = false;
 
     return bRet;
@@ -901,8 +943,6 @@ static void lcl_PreparePrinterOptions(
     }
 }
 
-enum class WorkingDocType { SOURCE, TARGET, COPY };
-
 static SfxObjectShell* lcl_CreateWorkingDocument(
     // input
     const WorkingDocType aType, const SwDoc* pSourceDoc,
@@ -1100,21 +1140,8 @@ bool SwDBManager::MergeMailFiles(SwWrtShell* pSourceShell,
             }
         }
 
-        SwDocShell* pSourceDocSh = pSourceShell->GetView().GetDocShell();
-
-        uno::Reference<document::XDocumentProperties> xSourceDocProps;
-        {
-            uno::Reference<document::XDocumentPropertiesSupplier>
-                xDPS(pSourceDocSh->GetModel(), uno::UNO_QUERY);
-            xSourceDocProps.set(xDPS->getDocumentProperties());
-            assert( xSourceDocProps.is() && "DocumentProperties is null" );
-        }
+        SwDocShell  *pSourceDocSh = pSourceShell->GetView().GetDocShell();
 
-        // Try saving the source document
-        SfxDispatcher* pSfxDispatcher = pSourceShell->GetView().GetViewFrame()->GetDispatcher();
-        if( !bMT_SHELL && pSourceDocSh->IsModified() )
-            pSfxDispatcher->Execute( pSourceDocSh->HasName() ? SID_SAVEDOC : SID_SAVEASDOC, SfxCallMode::SYNCHRON|SfxCallMode::RECORD);
-        if( bMT_SHELL || !pSourceDocSh->IsModified() )
         {
             // setup the output format
             const SfxFilter* pStoreToFilter = SwIoSystem::GetFileFilter(
@@ -2817,15 +2844,8 @@ void SwDBManager::ExecuteFormLetter( SwWrtShell& rSh,
         {
             {
                 {
-                    SwWrtShell  *pWorkShell;
-                    SwDoc       *pWorkDoc;
-                    SwDBManager *pWorkDocOrigDBManager = this;
-                    SfxObjectShellLock xWorkDocSh = lcl_CreateWorkingDocument(
-                        WorkingDocType::SOURCE, rSh.GetDoc(), nullptr,
-                        &pWorkDocOrigDBManager, nullptr, &pWorkShell, &pWorkDoc );
-
                     // prepare mail merge descriptor
-                    SwMergeDescriptor aMergeDesc( pImpl->pMergeDialog->GetMergeType(), *pWorkShell, aDescriptor );
+                    SwMergeDescriptor aMergeDesc( pImpl->pMergeDialog->GetMergeType(), rSh, aDescriptor );
                     aMergeDesc.sSaveToFilter = pImpl->pMergeDialog->GetSaveFilter();
                     aMergeDesc.bCreateSingleFile = pImpl->pMergeDialog->IsSaveSingleDoc();
                     aMergeDesc.sPath = INetURLObject::TryUrlFromSystemPathAsString(
@@ -2838,9 +2858,6 @@ void SwDBManager::ExecuteFormLetter( SwWrtShell& rSh,
                     }
 
                     MergeNew( aMergeDesc );
-
-                    pWorkDoc->SetDBManager( pWorkDocOrigDBManager );
-                    xWorkDocSh->DoClose();
                 }
             }
         }
commit 51e5b5a92b864ca3782542d0025fec73699ceacc
Author: Jan-Marek Glogowski <glogow at fbihome.de>
Date:   Wed Jan 27 11:51:29 2016 +0100

    MM: just show the print progress dialog for print
    
    Change-Id: I75a33c14f4a2b5ab404ce937e5d23392f6021a1b

diff --git a/sw/source/uibase/dbui/dbmgr.cxx b/sw/source/uibase/dbui/dbmgr.cxx
index f679fc9..1159f3f 100644
--- a/sw/source/uibase/dbui/dbmgr.cxx
+++ b/sw/source/uibase/dbui/dbmgr.cxx
@@ -1160,9 +1160,9 @@ bool SwDBManager::MergeMailFiles(SwWrtShell* pSourceShell,
             {
                 // construct the process dialog
                 pSourceWindow = &pSourceShell->GetView().GetEditWin();
-                if( ! pParent )
+                if( !pParent )
                     pParent = pSourceWindow;
-                if( bMT_SHELL )
+                if( !bMT_PRINTER )
                     pProgressDlg = VclPtr<CreateMonitor>::Create(
                         pParent, pParent != pSourceWindow );
                 else {
@@ -1211,7 +1211,7 @@ bool SwDBManager::MergeMailFiles(SwWrtShell* pSourceShell,
             // it can be manually computed from the source documents (for which we do layouts, so the page
             // count is known, and there is a blank page between each of them in the target document).
             int targetDocPageCount = 0;
-            if( !bIsMergeSilent && bMT_SHELL &&
+            if( !bIsMergeSilent && !bMT_PRINTER &&
                     lcl_getCountFromResultSet( nDocCount, pImpl->pMergeData->xResultSet ) )
                 static_cast<CreateMonitor*>( pProgressDlg.get() )->SetTotalCount( nDocCount );
 
@@ -1286,7 +1286,7 @@ bool SwDBManager::MergeMailFiles(SwWrtShell* pSourceShell,
                         if( bNeedsTempFiles )
                             aTempFileURL.reset( new INetURLObject(aTempFile->GetURL()));
                         if( !bIsMergeSilent ) {
-                            if( bMT_SHELL )
+                            if( !bMT_PRINTER )
                                 static_cast<CreateMonitor*>( pProgressDlg.get() )->SetCurrentPosition( nDocNo );
                             else {
                                 PrintMonitor *pPrintMonDlg = static_cast<PrintMonitor*>( pProgressDlg.get() );
commit f593c2d2276b412a5b4f09c1ceec97e768d982d8
Author: Jan-Marek Glogowski <glogow at fbihome.de>
Date:   Wed Jan 27 11:48:28 2016 +0100

    MM: fix silent mode on merge start
    
    We currently don't handle the change of silent mode during a running
    mail merge job correctly, so don't allow it.
    
    Change-Id: I2cb8cc1c737e93e8b2a90a6e73fb3e49008fe91d

diff --git a/sw/source/uibase/dbui/dbmgr.cxx b/sw/source/uibase/dbui/dbmgr.cxx
index fac3ce6..f679fc9 100644
--- a/sw/source/uibase/dbui/dbmgr.cxx
+++ b/sw/source/uibase/dbui/dbmgr.cxx
@@ -1031,6 +1031,7 @@ bool SwDBManager::MergeMailFiles(SwWrtShell* pSourceShell,
     //check if the doc is synchronized and contains at least one linked section
     const bool bSynchronizedDoc = pSourceShell->IsLabelDoc() && pSourceShell->GetSectionFormatCount() > 1;
     const bool bNeedsTempFiles = ( bMT_EMAIL || bMT_FILE );
+    const bool bIsMergeSilent = IsMergeSilent();
 
     bool bCheckSingleFile_ = rMergeDescriptor.bCreateSingleFile;
     if( bMT_EMAIL )
@@ -1155,7 +1156,7 @@ bool SwDBManager::MergeMailFiles(SwWrtShell* pSourceShell,
             vcl::Window *pSourceWindow = nullptr;
             VclPtr<CancelableDialog> pProgressDlg;
 
-            if( !IsMergeSilent() )
+            if( !bIsMergeSilent )
             {
                 // construct the process dialog
                 pSourceWindow = &pSourceShell->GetView().GetEditWin();
@@ -1210,7 +1211,7 @@ bool SwDBManager::MergeMailFiles(SwWrtShell* pSourceShell,
             // it can be manually computed from the source documents (for which we do layouts, so the page
             // count is known, and there is a blank page between each of them in the target document).
             int targetDocPageCount = 0;
-            if( !IsMergeSilent() && bMT_SHELL &&
+            if( !bIsMergeSilent && bMT_SHELL &&
                     lcl_getCountFromResultSet( nDocCount, pImpl->pMergeData->xResultSet ) )
                 static_cast<CreateMonitor*>( pProgressDlg.get() )->SetTotalCount( nDocCount );
 
@@ -1284,7 +1285,7 @@ bool SwDBManager::MergeMailFiles(SwWrtShell* pSourceShell,
                         std::unique_ptr< INetURLObject > aTempFileURL;
                         if( bNeedsTempFiles )
                             aTempFileURL.reset( new INetURLObject(aTempFile->GetURL()));
-                        if (!IsMergeSilent()) {
+                        if( !bIsMergeSilent ) {
                             if( bMT_SHELL )
                                 static_cast<CreateMonitor*>( pProgressDlg.get() )->SetCurrentPosition( nDocNo );
                             else {
@@ -1388,7 +1389,7 @@ bool SwDBManager::MergeMailFiles(SwWrtShell* pSourceShell,
                                 uno::Sequence< beans::PropertyValue > aOptions( rMergeDescriptor.aPrintOptions );
                                 lcl_PreparePrinterOptions( rMergeDescriptor.aPrintOptions, false, aOptions );
 
-                                pWorkView->StartPrint( aOptions, IsMergeSilent(), rMergeDescriptor.bPrintAsync );
+                                pWorkView->StartPrint( aOptions, bIsMergeSilent, rMergeDescriptor.bPrintAsync );
                                 // some GetPrinter functions have a true default, so keep the false
                                 SfxPrinter* pDocPrt = pWorkView->GetPrinter( false );
                                 JobSetup aJobSetup = pDocPrt ? pDocPrt->GetJobSetup() : pWorkView->GetJobSetup();
@@ -1513,7 +1514,7 @@ bool SwDBManager::MergeMailFiles(SwWrtShell* pSourceShell,
                     // print the target document
                     uno::Sequence< beans::PropertyValue > aOptions( rMergeDescriptor.aPrintOptions );
                     lcl_PreparePrinterOptions( rMergeDescriptor.aPrintOptions, true, aOptions );
-                    pTargetView->ExecPrint( aOptions, IsMergeSilent(), rMergeDescriptor.bPrintAsync );
+                    pTargetView->ExecPrint( aOptions, bIsMergeSilent, rMergeDescriptor.bPrintAsync );
                 }
 
                 if( IsMergeOk() && bMT_SHELL )
commit c90d63751268b23df4fe00a858898a84c2605224
Author: Jan-Marek Glogowski <glogow at fbihome.de>
Date:   Wed Jan 27 11:42:45 2016 +0100

    MM: move mail creation into a local function
    
    And also use C++11 range-based for loop loops.
    
    Change-Id: I7bafc419a21cdd6bb7aaed7d67b640409d308f79

diff --git a/sw/source/uibase/dbui/dbmgr.cxx b/sw/source/uibase/dbui/dbmgr.cxx
index 49d33bf..fac3ce6 100644
--- a/sw/source/uibase/dbui/dbmgr.cxx
+++ b/sw/source/uibase/dbui/dbmgr.cxx
@@ -959,6 +959,60 @@ static SfxObjectShell* lcl_CreateWorkingDocument(
     return xWorkObjectShell;
 }
 
+uno::Reference< mail::XMailMessage > lcl_CreateMailFromDoc(
+    const SwMergeDescriptor &rMergeDescriptor,
+    const OUString &sFileURL, const OUString &sMailRecipient,
+    const OUString &sMailBodyMimeType, const rtl_TextEncoding &sMailEncoding,
+    const OUString &sAttachmentMimeType )
+{
+    SwMailMessage* pMessage = new SwMailMessage;
+    uno::Reference< mail::XMailMessage > xMessage = pMessage;
+    if( rMergeDescriptor.pMailMergeConfigItem->IsMailReplyTo() )
+        pMessage->setReplyToAddress(rMergeDescriptor.pMailMergeConfigItem->GetMailReplyTo());
+    pMessage->addRecipient( sMailRecipient );
+    pMessage->SetSenderAddress( rMergeDescriptor.pMailMergeConfigItem->GetMailAddress() );
+
+    OUString sBody;
+    if( rMergeDescriptor.bSendAsAttachment )
+    {
+        sBody = rMergeDescriptor.sMailBody;
+        mail::MailAttachment aAttach;
+        aAttach.Data = new SwMailTransferable( sFileURL,
+            rMergeDescriptor.sAttachmentName, sAttachmentMimeType );
+        aAttach.ReadableName = rMergeDescriptor.sAttachmentName;
+        pMessage->addAttachment( aAttach );
+    }
+    else
+    {
+        //read in the temporary file and use it as mail body
+        SfxMedium aMedium( sFileURL, StreamMode::READ );
+        SvStream* pInStream = aMedium.GetInStream();
+        assert( pInStream && "no output file created?" );
+        if( pInStream )
+            return xMessage;
+
+        pInStream->SetStreamCharSet( sMailEncoding );
+        OString sLine;
+        while ( pInStream->ReadLine( sLine ) )
+        {
+            sBody += OStringToOUString( sLine, sMailEncoding );
+            sBody += "\n";
+        }
+    }
+    pMessage->setSubject( rMergeDescriptor.sSubject );
+    uno::Reference< datatransfer::XTransferable> xBody =
+                new SwMailTransferable( sBody, sMailBodyMimeType );
+    pMessage->setBody( xBody );
+
+    for( const OUString& sCcRecipient : rMergeDescriptor.aCopiesTo )
+        pMessage->addCcRecipient( sCcRecipient );
+    for( const OUString& sBccRecipient : rMergeDescriptor.aBlindCopiesTo )
+        pMessage->addBccRecipient( sBccRecipient );
+
+    xMessage = pMessage;
+    return xMessage;
+}
+
 /**
  * Please have a look at the README in the same directory, before you make
  * larger changes in this function!
@@ -1369,70 +1423,17 @@ bool SwDBManager::MergeMailFiles(SwWrtShell* pSourceShell,
 
                             if( bMT_EMAIL && !IsMergeError() )
                             {
+                                // schedule file for later removal
+                                aFilesToRemove.push_back( sFileURL );
+
+                                uno::Reference< mail::XMailMessage > xMessage = lcl_CreateMailFromDoc(
+                                    rMergeDescriptor, sFileURL, sColumnData, sMailBodyMimeType,
+                                    sMailEncoding, pStoreToFilter->GetMimeType() );
+                                if( xMessage.is() )
                                 {
-                                    SwMailMessage* pMessage = new SwMailMessage;
-                                    uno::Reference< mail::XMailMessage > xMessage = pMessage;
-                                    if(rMergeDescriptor.pMailMergeConfigItem->IsMailReplyTo())
-                                        pMessage->setReplyToAddress(rMergeDescriptor.pMailMergeConfigItem->GetMailReplyTo());
-                                    pMessage->addRecipient( sColumnData );
-                                    pMessage->SetSenderAddress( rMergeDescriptor.pMailMergeConfigItem->GetMailAddress() );
-                                    OUString sBody;
-
-                                    if(rMergeDescriptor.bSendAsAttachment)
-                                    {
-                                        sBody = rMergeDescriptor.sMailBody;
-                                        mail::MailAttachment aAttach;
-                                        aAttach.Data = new SwMailTransferable(
-                                                sFileURL,
-                                                rMergeDescriptor.sAttachmentName,
-                                                pStoreToFilter->GetMimeType());
-                                        aAttach.ReadableName = rMergeDescriptor.sAttachmentName;
-                                        pMessage->addAttachment( aAttach );
-                                    }
-                                    else
-                                    {
-                                        {
-                                            //read in the temporary file and use it as mail body
-                                            SfxMedium aMedium( sFileURL, StreamMode::READ);
-                                            SvStream* pInStream = aMedium.GetInStream();
-                                            assert( pInStream && "no output file created?" );
-                                            if(pInStream)
-                                            {
-                                                pInStream->SetStreamCharSet( sMailEncoding );
-                                                OString sLine;
-                                                bool bDone = pInStream->ReadLine( sLine );
-                                                while ( bDone )
-                                                {
-                                                    sBody += OStringToOUString( sLine, sMailEncoding );
-                                                    sBody += "\n";
-                                                    bDone = pInStream->ReadLine( sLine );
-                                                }
-                                            }
-                                        }
-                                    }
-                                    pMessage->setSubject( rMergeDescriptor.sSubject );
-                                    uno::Reference< datatransfer::XTransferable> xBody =
-                                                new SwMailTransferable(
-                                                    sBody, sMailBodyMimeType);
-                                    pMessage->setBody( xBody );
-
-                                    if(rMergeDescriptor.aCopiesTo.getLength())
-                                    {
-                                        const OUString* pCopies = rMergeDescriptor.aCopiesTo.getConstArray();
-                                        for( sal_Int32 nToken = 0; nToken < rMergeDescriptor.aCopiesTo.getLength(); ++nToken)
-                                            pMessage->addCcRecipient( pCopies[nToken] );
-                                    }
-                                    if(rMergeDescriptor.aBlindCopiesTo.getLength())
-                                    {
-                                        const OUString* pCopies = rMergeDescriptor.aBlindCopiesTo.getConstArray();
-                                        for( sal_Int32 nToken = 0; nToken < rMergeDescriptor.aBlindCopiesTo.getLength(); ++nToken)
-                                            pMessage->addBccRecipient( pCopies[nToken] );
-                                    }
                                     xMailDispatcher->enqueueMailMessage( xMessage );
-                                    if(!xMailDispatcher->isStarted())
+                                    if( !xMailDispatcher->isStarted() )
                                         xMailDispatcher->start();
-                                    //schedule for removal
-                                    aFilesToRemove.push_back(sFileURL);
                                 }
                             }
                         }
commit 87891c5e9e49d653dd65e1285e71ba006b8aef13
Author: Jan-Marek Glogowski <glogow at fbihome.de>
Date:   Mon Jan 25 19:36:26 2016 +0100

    MM: don't register files in recently used...
    
    ... in email and !bCreateSingleFile file mode. Also saves a bunch
    of instructions. For my simple document it was ~10% of the save
    time and 75% is the creation of the preview thumbnails...
    
    Change-Id: I14f7092007b1acfed6cbe0f2f4cd6eaecd32b514

diff --git a/sw/source/uibase/dbui/dbmgr.cxx b/sw/source/uibase/dbui/dbmgr.cxx
index 781b53a..49d33bf 100644
--- a/sw/source/uibase/dbui/dbmgr.cxx
+++ b/sw/source/uibase/dbui/dbmgr.cxx
@@ -853,7 +853,11 @@ static bool lcl_SaveDoc(
         rWorkShell.ConvertFieldsToText();
 
     bool bAnyError = !xObjectShell->DoSaveAs(*pDstMed);
-    xObjectShell->DoSaveCompleted(pDstMed);
+
+    // Actually this should be a bool... so in case of email and individual
+    // files, where this is set, we skip the the recently used handling
+    if( !decodedURL )
+        xObjectShell->DoSaveCompleted( pDstMed );
     bAnyError = bAnyError || xObjectShell->GetError();
     if( bAnyError )
     {
commit cd5d19d6f205522cd4f619d95339a221510af8f5
Author: Jan-Marek Glogowski <glogow at fbihome.de>
Date:   Mon Jan 25 18:10:29 2016 +0100

    MM: use working doc DB manager on save
    
    This is related to tdf#97318 but doesn't fix it, as the wizard
    works with a single merged document, which is split later.
    
    When saving the working document in !bCreateSingleFile mode, we
    have to restore the documents DB manager for two reasons:
    
    1. We otherwise would save the whole database content.
    2. We crash with embedded databases of the original DB manager.
    
    Change-Id: I9b209854703ec95c2c63c83019e857f2d26f753d

diff --git a/sw/source/uibase/dbui/dbmgr.cxx b/sw/source/uibase/dbui/dbmgr.cxx
index 0fde862..781b53a 100644
--- a/sw/source/uibase/dbui/dbmgr.cxx
+++ b/sw/source/uibase/dbui/dbmgr.cxx
@@ -1345,6 +1345,12 @@ bool SwDBManager::MergeMailFiles(SwWrtShell* pSourceShell,
                         else
                         {
                             assert( bNeedsTempFiles );
+                            assert( pWorkShell->IsExpFieldsLocked() );
+
+                            // fields are locked, so it's fine to
+                            // restore the old / empty DB manager for save
+                            pWorkDoc->SetDBManager( pWorkDocOrigDBManager );
+
                             // save merged document
                             OUString sFileURL;
                             if( !lcl_SaveDoc( aTempFileURL.get(), pStoreToFilter, pStoreToFilterOptions,
@@ -1353,6 +1359,10 @@ bool SwDBManager::MergeMailFiles(SwWrtShell* pSourceShell,
                             {
                                 m_aMergeStatus = MergeStatus::ERROR;
                             }
+
+                            // back to the MM DB manager
+                            pWorkDoc->SetDBManager( this );
+
                             if( bMT_EMAIL && !IsMergeError() )
                             {
                                 {
commit 1d1fd4d2b6ee1db407a8f16dee84900b4f0ff5b2
Author: Jan-Marek Glogowski <glogow at fbihome.de>
Date:   Mon Jan 25 17:48:15 2016 +0100

    MM: correctly handle directory in dialog
    
    The directory selection dialog expects an URL. For convenience
    we present file URIs in the systems local file notation.
    
    So we need to convert the location notation to URI for the dialog.
    And since its a editable entry, append a directory delimiter to
    the value of the entry.
    
    Change-Id: Idff6f7d4b135eef087c61560b0603b9a6669dbf7

diff --git a/sw/source/ui/envelp/mailmrge.cxx b/sw/source/ui/envelp/mailmrge.cxx
index 107d8a7..34c7271 100644
--- a/sw/source/ui/envelp/mailmrge.cxx
+++ b/sw/source/ui/envelp/mailmrge.cxx
@@ -579,6 +579,7 @@ IMPL_LINK_NOARG_TYPED(SwMailMergeDlg, InsertPathHdl, Button*, void)
         SvtPathOptions aPathOpt;
         sPath = aPathOpt.GetWorkPath();
     }
+    sPath = INetURLObject::TryUrlFromSystemPathAsString( sPath, true );
 
     uno::Reference< XComponentContext > xContext( ::comphelper::getProcessComponentContext() );
     uno::Reference < XFolderPicker2 > xFP = FolderPicker::create(xContext);
diff --git a/sw/source/uibase/dbui/dbmgr.cxx b/sw/source/uibase/dbui/dbmgr.cxx
index dc551c1..0fde862 100644
--- a/sw/source/uibase/dbui/dbmgr.cxx
+++ b/sw/source/uibase/dbui/dbmgr.cxx
@@ -2812,7 +2812,10 @@ void SwDBManager::ExecuteFormLetter( SwWrtShell& rSh,
                     SwMergeDescriptor aMergeDesc( pImpl->pMergeDialog->GetMergeType(), *pWorkShell, aDescriptor );
                     aMergeDesc.sSaveToFilter = pImpl->pMergeDialog->GetSaveFilter();
                     aMergeDesc.bCreateSingleFile = pImpl->pMergeDialog->IsSaveSingleDoc();
-                    aMergeDesc.sPath = pImpl->pMergeDialog->GetPath(true);
+                    aMergeDesc.sPath = INetURLObject::TryUrlFromSystemPathAsString(
+                        pImpl->pMergeDialog->GetPath( true ) );
+                    if( !aMergeDesc.sPath.isEmpty() && !aMergeDesc.sPath.endsWith("/") )
+                        aMergeDesc.sPath += "/";
                     if( !aMergeDesc.bCreateSingleFile && pImpl->pMergeDialog->IsGenerateFromDataBase() )
                     {
                         aMergeDesc.sDBcolumn = pImpl->pMergeDialog->GetColumnName();
commit fb56427822358b3cc21e0b9d0f1719a1c4b4334c
Author: Jan-Marek Glogowski <glogow at fbihome.de>
Date:   Fri Jan 22 21:25:11 2016 +0100

    tdf#96914 MM: don't round trip the source document
    
    To get a unmodified document, the mail merge via File -> Print
    used to write a document and reload it. This is not a problem with
    normal documents, but with embedded databases this results in a
    second database with the same name, which disposes the first
    registered database and the xResultSet from the mail merge dialog.
    
    As a workaround this just creates an internal copy, sets the
    correct database settings and resets the modified status.
    
    We still need a more general solution to handle documents with the
    same embedded DB name in a sane way, probably by making the embedded
    database a private object of the documents database manager.
    
    Change-Id: I20ddea30196d65cb89f69977867f012816ec6001

diff --git a/sw/inc/doc.hxx b/sw/inc/doc.hxx
index 4f9eec3..b971a1c 100644
--- a/sw/inc/doc.hxx
+++ b/sw/inc/doc.hxx
@@ -1623,7 +1623,7 @@ public:
     ::sw::UndoManager      & GetUndoManager();
     ::sw::UndoManager const& GetUndoManager() const;
 
-    SfxObjectShell* CreateCopy(bool bCallInitNew) const;
+    SfxObjectShell* CreateCopy(bool bCallInitNew, bool bEmpty) const;
     SwNodeIndex AppendDoc(const SwDoc& rSource, sal_uInt16 nStartPageNumber,
                  bool bDeletePrevious = false, int physicalPageOffset = 0,
                  const sal_uLong nDocNo = 1);
diff --git a/sw/source/core/doc/docnew.cxx b/sw/source/core/doc/docnew.cxx
index 4d7e04a..74908dd 100644
--- a/sw/source/core/doc/docnew.cxx
+++ b/sw/source/core/doc/docnew.cxx
@@ -867,7 +867,7 @@ void SwDoc::ReplaceCompatibilityOptions(const SwDoc& rSource)
     ((idx).GetNode().GetIndex() - GetNodes().GetEndOfExtras().GetIndex() - 1)
 #endif
 
-SfxObjectShell* SwDoc::CreateCopy(bool bCallInitNew ) const
+SfxObjectShell* SwDoc::CreateCopy( bool bCallInitNew, bool bEmpty ) const
 {
     SwDoc* pRet = new SwDoc;
 
@@ -890,14 +890,17 @@ SfxObjectShell* SwDoc::CreateCopy(bool bCallInitNew ) const
 
     pRet->ReplaceStyles(*this);
 
+    if( !bEmpty )
+    {
 #ifdef DBG_UTIL
-    SAL_INFO( "sw.createcopy", "CC-Nd-Src: " << CNTNT_DOC( this ) );
-    SAL_INFO( "sw.createcopy", "CC-Nd: " << CNTNT_DOC( pRet ) );
+        SAL_INFO( "sw.createcopy", "CC-Nd-Src: " << CNTNT_DOC( this ) );
+        SAL_INFO( "sw.createcopy", "CC-Nd: " << CNTNT_DOC( pRet ) );
 #endif
-    pRet->AppendDoc(*this, 0, bCallInitNew, 0, 0);
+        pRet->AppendDoc(*this, 0, bCallInitNew, 0, 0);
 #ifdef DBG_UTIL
-    SAL_INFO( "sw.createcopy", "CC-Nd: " << CNTNT_DOC( pRet ) );
+        SAL_INFO( "sw.createcopy", "CC-Nd: " << CNTNT_DOC( pRet ) );
 #endif
+    }
 
     // remove the temporary shell if it is there as it was done before
     pRet->SetTmpDocShell( nullptr );
diff --git a/sw/source/uibase/dbui/dbmgr.cxx b/sw/source/uibase/dbui/dbmgr.cxx
index 4365b98..dc551c1 100644
--- a/sw/source/uibase/dbui/dbmgr.cxx
+++ b/sw/source/uibase/dbui/dbmgr.cxx
@@ -41,7 +41,6 @@
 #include <com/sun/star/ui/dialogs/XFilePicker2.hpp>
 #include <com/sun/star/ui/dialogs/XFilterManager.hpp>
 #include <com/sun/star/uno/XNamingService.hpp>
-#include <com/sun/star/util/XCloseable.hpp>
 #include <com/sun/star/beans/XPropertySet.hpp>
 #include <sfx2/fcontnr.hxx>
 #include <sfx2/filedlghelper.hxx>
@@ -136,6 +135,7 @@
 #include <calc.hxx>
 #include <dbfld.hxx>
 #include <DocumentFieldsManager.hxx>
+#include <IDocumentState.hxx>
 
 #include <memory>
 #include <comphelper/propertysequence.hxx>
@@ -897,6 +897,64 @@ static void lcl_PreparePrinterOptions(
     }
 }
 
+enum class WorkingDocType { SOURCE, TARGET, COPY };
+
+static SfxObjectShell* lcl_CreateWorkingDocument(
+    // input
+    const WorkingDocType aType, const SwDoc* pSourceDoc,
+    // optional input
+    const vcl::Window *pSourceWindow,
+    // optional in and output to swap the DB manager
+    SwDBManager** const pDBManager,
+    // optional output
+    SwView** const pView, SwWrtShell** const pWrtShell, SwDoc** const pDoc )
+{
+    SfxObjectShellRef xWorkObjectShell = pSourceDoc->CreateCopy( true, (aType == WorkingDocType::TARGET) );
+    SfxViewFrame* pWorkFrame = SfxViewFrame::LoadHiddenDocument( *xWorkObjectShell, 0 );
+
+    if( pSourceWindow )
+    {
+        // the created window has to be located at the same position as the source window
+        vcl::Window& rTargetWindow = pWorkFrame->GetFrame().GetWindow();
+        rTargetWindow.SetPosPixel( pSourceWindow->GetPosPixel() );
+    }
+
+    SwView* pWorkView = static_cast< SwView* >( pWorkFrame->GetViewShell() );
+    SwWrtShell* pWorkWrtShell = pWorkView->GetWrtShellPtr();
+    pWorkView->AttrChangedNotify( pWorkWrtShell );// in order for SelectShell to be called
+    SwDoc* pWorkDoc = pWorkWrtShell->GetDoc();
+    pWorkDoc->ReplaceDocumentProperties( *pSourceDoc );
+
+    if( aType == WorkingDocType::TARGET )
+    {
+        assert( !pDBManager );
+        pWorkDoc->SetInMailMerge( true );
+    }
+    else
+    {
+        // We have to swap the DBmanager of the new doc, so we also need input
+        assert( pDBManager && *pDBManager );
+        SwDBManager *pWorkDBManager = pWorkDoc->GetDBManager();
+        pWorkDoc->SetDBManager( *pDBManager );
+        *pDBManager = pWorkDBManager;
+
+        if( aType == WorkingDocType::SOURCE )
+        {
+            // the GetDBData call constructs the data, if it's missing - kind of const...
+            pWorkWrtShell->ChgDBData( const_cast<SwDoc*>(pSourceDoc)->GetDBData() );
+            pWorkDoc->getIDocumentState().ResetModified();
+        }
+        else
+            pWorkDoc->getIDocumentLinksAdministration().EmbedAllLinks();
+    }
+
+    if( pView )     *pView     = pWorkView;
+    if( pWrtShell ) *pWrtShell = pWorkWrtShell;
+    if( pDoc )      *pDoc      = pWorkDoc;
+
+    return xWorkObjectShell;
+}
+
 /**
  * Please have a look at the README in the same directory, before you make
  * larger changes in this function!
@@ -983,8 +1041,6 @@ bool SwDBManager::MergeMailFiles(SwWrtShell* pSourceShell,
             }
         }
 
-        // Try saving the source document
-        SfxDispatcher* pSfxDispatcher = pSourceShell->GetView().GetViewFrame()->GetDispatcher();
         SwDocShell* pSourceDocSh = pSourceShell->GetView().GetDocShell();
 
         uno::Reference<document::XDocumentProperties> xSourceDocProps;
@@ -995,6 +1051,8 @@ bool SwDBManager::MergeMailFiles(SwWrtShell* pSourceShell,
             assert( xSourceDocProps.is() && "DocumentProperties is null" );
         }
 
+        // Try saving the source document
+        SfxDispatcher* pSfxDispatcher = pSourceShell->GetView().GetViewFrame()->GetDispatcher();
         if( !bMT_SHELL && pSourceDocSh->IsModified() )
             pSfxDispatcher->Execute( pSourceDocSh->HasName() ? SID_SAVEDOC : SID_SAVEASDOC, SfxCallMode::SYNCHRON|SfxCallMode::RECORD);
         if( bMT_SHELL || !pSourceDocSh->IsModified() )
@@ -1064,37 +1122,15 @@ bool SwDBManager::MergeMailFiles(SwWrtShell* pSourceShell,
             if( bCreateSingleFile )
             {
                 // create a target docshell to put the merged document into
-                xTargetDocShell = new SwDocShell( SfxObjectCreateMode::STANDARD );
-                xTargetDocShell->DoInitNew();
+                xTargetDocShell = lcl_CreateWorkingDocument( WorkingDocType::TARGET,
+                    pSourceDocSh->GetDoc(), bMT_SHELL ? pSourceWindow : nullptr,
+                    nullptr, &pTargetView, &pTargetShell, &pTargetDoc );
                 if (nMaxDumpDocs)
                     lcl_SaveDebugDoc( xTargetDocShell, "MergeDoc" );
-                SfxViewFrame* pTargetFrame = SfxViewFrame::LoadHiddenDocument( *xTargetDocShell, 0 );
-                if (bMT_SHELL && pSourceWindow) {
-                    //the created window has to be located at the same position as the source window
-                    vcl::Window& rTargetWindow = pTargetFrame->GetFrame().GetWindow();
-                    rTargetWindow.SetPosPixel(pSourceWindow->GetPosPixel());
-                }
-
-                pTargetView = static_cast<SwView*>( pTargetFrame->GetViewShell() );
-
-                //initiate SelectShell() to create sub shells
-                pTargetView->AttrChangedNotify( &pTargetView->GetWrtShell() );
-                pTargetShell = pTargetView->GetWrtShellPtr();
-                pTargetDoc = pTargetShell->GetDoc();
-                pTargetDoc->SetInMailMerge(true);
 
-                //copy the styles from the source to the target document
-                pTargetView->GetDocShell()->_LoadStyles( *pSourceDocSh, true );
-
-                //determine the page style and number used at the start of the source document
+                // determine the page style and number used at the start of the source document
                 pSourceShell->SttEndDoc(true);
                 nStartingPageNo = pSourceShell->GetVirtPageNum();
-
-                // copy compatibility options
-                pTargetDoc->ReplaceCompatibilityOptions( *pSourceShell->GetDoc() );
-                // #72821# copy dynamic defaults
-                pTargetDoc->ReplaceDefaults( *pSourceShell->GetDoc() );
-                pTargetDoc->ReplaceDocumentProperties( *pSourceShell->GetDoc() );
             }
 
             // Progress, to prohibit KeyInputs
@@ -1131,6 +1167,7 @@ bool SwDBManager::MergeMailFiles(SwWrtShell* pSourceShell,
             SwView*            pWorkView             = nullptr;
             SwDoc*             pWorkDoc              = nullptr;
             SwDBManager*       pWorkDocOrigDBManager = nullptr;
+            SwWrtShell*        pWorkShell            = nullptr;
             bool               bWorkDocInitialized   = false;
 
             do
@@ -1211,41 +1248,29 @@ bool SwDBManager::MergeMailFiles(SwWrtShell* pSourceShell,
                         if( !bWorkDocInitialized || bCreateSingleFile || bIsPDFeport )
                         {
                             assert( !xWorkDocSh.Is());
-                            // copy the source document
-                            xWorkDocSh = pSourceDocSh->GetDoc()->CreateCopy( true );
-
-                            //create a view frame for the document
-                            pWorkView = static_cast< SwView* >( SfxViewFrame::LoadHiddenDocument( *xWorkDocSh, 0 )->GetViewShell() );
-                            //request the layout calculation
-                            SwWrtShell& rWorkShell = pWorkView->GetWrtShell();
-                            pWorkView->AttrChangedNotify( &rWorkShell );// in order for SelectShell to be called
-
-                            pWorkDoc = rWorkShell.GetDoc();
-                            pWorkDoc->ReplaceDocumentProperties( *pSourceDocSh->GetDoc());
+                            pWorkDocOrigDBManager = this;
+                            xWorkDocSh = lcl_CreateWorkingDocument( WorkingDocType::COPY,
+                                pSourceDocSh->GetDoc(), nullptr, &pWorkDocOrigDBManager,
+                                &pWorkView, &pWorkShell, &pWorkDoc );
                             if ( (nMaxDumpDocs < 0) || (nDocNo <= nMaxDumpDocs) )
                                 lcl_SaveDebugDoc( xWorkDocSh, "WorkDoc", nDocNo );
-                            pWorkDocOrigDBManager = pWorkDoc->GetDBManager();
-                            pWorkDoc->SetDBManager( this );
-                            pWorkDoc->getIDocumentLinksAdministration().EmbedAllLinks();
 
                             // #i69458# lock fields to prevent access to the result set while calculating layout
                             // tdf#92324: and do not unlock: keep document locked during printing to avoid
                             // ExpFields update during printing, generation of preview, etc.
-                            rWorkShell.LockExpFields();
-                            rWorkShell.CalcLayout();
+                            pWorkShell->LockExpFields();
+                            pWorkShell->CalcLayout();
                         }
 
-                        SwWrtShell& rWorkShell = pWorkView->GetWrtShell();
-
                         EMIT_SW_EVENT(FIELD_MERGE, xWorkDocSh);
 
                         // tdf#92324: Allow ExpFields update only by explicit instruction to avoid
                         // database cursor movement on any other fields update, for example during
                         // print preview and other operations
-                        if ( rWorkShell.IsExpFieldsLocked() )
-                            rWorkShell.UnlockExpFields();
-                        rWorkShell.SwViewShell::UpdateFields();
-                        rWorkShell.LockExpFields();
+                        if ( pWorkShell->IsExpFieldsLocked() )
+                            pWorkShell->UnlockExpFields();
+                        pWorkShell->SwViewShell::UpdateFields();
+                        pWorkShell->LockExpFields();
 
                         EMIT_SW_EVENT(FIELD_MERGE_FINISHED, xWorkDocSh);
 
@@ -1268,11 +1293,11 @@ bool SwDBManager::MergeMailFiles(SwWrtShell* pSourceShell,
                             // prepare working copy and target to append
 
                             pWorkDoc->RemoveInvisibleContent();
-                            rWorkShell.ConvertFieldsToText();
-                            rWorkShell.SetNumberingRestart();
+                            pWorkShell->ConvertFieldsToText();
+                            pWorkShell->SetNumberingRestart();
                             if( bSynchronizedDoc )
                             {
-                                lcl_RemoveSectionLinks( rWorkShell );
+                                lcl_RemoveSectionLinks( *pWorkShell );
                             }
 
                             if ( (nMaxDumpDocs < 0) || (nDocNo <= nMaxDumpDocs) )
@@ -1281,9 +1306,9 @@ bool SwDBManager::MergeMailFiles(SwWrtShell* pSourceShell,
                             // append the working document to the target document
                             if( targetDocPageCount % 2 == 1 )
                                 ++targetDocPageCount; // Docs always start on odd pages (so offset must be even).
-                            SwNodeIndex appendedDocStart = pTargetDoc->AppendDoc(*rWorkShell.GetDoc(),
+                            SwNodeIndex appendedDocStart = pTargetDoc->AppendDoc( *pWorkDoc,
                                 nStartingPageNo, !bWorkDocInitialized, targetDocPageCount, nDocNo);
-                            targetDocPageCount += rWorkShell.GetPageCnt();
+                            targetDocPageCount += pWorkShell->GetPageCnt();
 
                             if ( (nMaxDumpDocs < 0) || (nDocNo <= nMaxDumpDocs) )
                                 lcl_SaveDebugDoc( xTargetDocShell, "MergeDoc" );
@@ -1324,7 +1349,7 @@ bool SwDBManager::MergeMailFiles(SwWrtShell* pSourceShell,
                             OUString sFileURL;
                             if( !lcl_SaveDoc( aTempFileURL.get(), pStoreToFilter, pStoreToFilterOptions,
                                               &rMergeDescriptor.aSaveToFilterData, bIsPDFeport,
-                                              xWorkDocSh, rWorkShell, &sFileURL ) )
+                                              xWorkDocSh, *pWorkShell, &sFileURL ) )
                             {
                                 m_aMergeStatus = MergeStatus::ERROR;
                             }
@@ -2703,7 +2728,7 @@ void SwDBManager::LoadAndRegisterEmbeddedDataSource(const SwDBData& rData, const
     if (sDataSource.isEmpty())
         sDataSource = "EmbeddedDatabase";
 
-    SwDBManager::RevokeDataSource(rData.sDataSource);
+    SwDBManager::RevokeDataSource( sDataSource );
 
     // Encode the stream name and the real path into a single URL.
     const INetURLObject& rURLObject = rDocShell.GetMedium()->GetURLObject();
@@ -2712,7 +2737,7 @@ void SwDBManager::LoadAndRegisterEmbeddedDataSource(const SwDBData& rData, const
     aURL += "/" + INetURLObject::encode(m_sEmbeddedName, INetURLObject::PART_FPATH, INetURLObject::ENCODE_ALL);
 
     uno::Reference<uno::XInterface> xDataSource(xDatabaseContext->getByName(aURL), uno::UNO_QUERY);
-    xDatabaseContext->registerObject(rData.sDataSource, xDataSource);
+    xDatabaseContext->registerObject( sDataSource, xDataSource );
 }
 
 void SwDBManager::ExecuteFormLetter( SwWrtShell& rSh,
@@ -2774,47 +2799,17 @@ void SwDBManager::ExecuteFormLetter( SwWrtShell& rSh,
 
         EMIT_SW_EVENT(MAIL_MERGE, xDocShell);
         {
-            //copy rSh to aTempFile
-            OUString sTempURL;
-            const SfxFilter *pSfxFlt = SwIoSystem::GetFilterOfFormat(
-                        FILTER_XML,
-                        SwDocShell::Factory().GetFilterContainer() );
-            try
-            {
-                uno::Sequence< beans::PropertyValue > aValues(1);
-                beans::PropertyValue* pValues = aValues.getArray();
-                pValues[0].Name = "FilterName";
-                pValues[0].Value <<= OUString(pSfxFlt->GetFilterName());
-                uno::Reference< frame::XStorable > xStore( xDocShell->GetModel(), uno::UNO_QUERY);
-                sTempURL = URIHelper::SmartRel2Abs( INetURLObject(), utl::TempFile::CreateTempName() );
-                xStore->storeToURL( sTempURL, aValues );
-            }
-            catch(const uno::Exception&)
             {
-            }
-            if( xDocShell->GetError() )
-            {
-                // error message ??
-                ErrorHandler::HandleError( xDocShell->GetError() );
-            }
-            else
-            {
-                // the shell will be explicitly closed, but it is more safe to use SfxObjectShellLock here
-                // especially for the case that the loading has failed
-                SfxObjectShellLock xWorkDocSh( new SwDocShell( SfxObjectCreateMode::INTERNAL ));
-                SfxMedium* pWorkMed = new SfxMedium( sTempURL, STREAM_STD_READ );
-                pWorkMed->SetFilter( pSfxFlt );
-                if( xWorkDocSh->DoLoad(pWorkMed) )
                 {
-                    SfxViewFrame *pFrame = SfxViewFrame::LoadHiddenDocument( *xWorkDocSh, 0 );
-                    SwView *pView = static_cast<SwView*>( pFrame->GetViewShell() );
-                    pView->AttrChangedNotify( &pView->GetWrtShell() );// in order for SelectShell to be called
-                    //set the current DBManager
-                    SwDoc* pWorkDoc = pView->GetWrtShell().GetDoc();
-                    SwDBManager* pWorkDocOrigDBManager = pWorkDoc->GetDBManager();
-                    pWorkDoc->SetDBManager( this );
-
-                    SwMergeDescriptor aMergeDesc( pImpl->pMergeDialog->GetMergeType(), pView->GetWrtShell(), aDescriptor );
+                    SwWrtShell  *pWorkShell;
+                    SwDoc       *pWorkDoc;
+                    SwDBManager *pWorkDocOrigDBManager = this;
+                    SfxObjectShellLock xWorkDocSh = lcl_CreateWorkingDocument(
+                        WorkingDocType::SOURCE, rSh.GetDoc(), nullptr,
+                        &pWorkDocOrigDBManager, nullptr, &pWorkShell, &pWorkDoc );
+
+                    // prepare mail merge descriptor
+                    SwMergeDescriptor aMergeDesc( pImpl->pMergeDialog->GetMergeType(), *pWorkShell, aDescriptor );
                     aMergeDesc.sSaveToFilter = pImpl->pMergeDialog->GetSaveFilter();
                     aMergeDesc.bCreateSingleFile = pImpl->pMergeDialog->IsSaveSingleDoc();
                     aMergeDesc.sPath = pImpl->pMergeDialog->GetPath(true);
@@ -2823,27 +2818,12 @@ void SwDBManager::ExecuteFormLetter( SwWrtShell& rSh,
                         aMergeDesc.sDBcolumn = pImpl->pMergeDialog->GetColumnName();
                     }
 
-                    MergeNew(aMergeDesc);
+                    MergeNew( aMergeDesc );
 
                     pWorkDoc->SetDBManager( pWorkDocOrigDBManager );
-                    //close the temporary file
-                    uno::Reference< util::XCloseable > xClose( xWorkDocSh->GetModel(), uno::UNO_QUERY );

... etc. - the rest is truncated


More information about the Libreoffice-commits mailing list