summaryrefslogtreecommitdiff
path: root/sw/source/ui/dbui/mmresultdialogs.cxx
blob: 3794f9f861c94ad1614a5f4e595d6dbdeae4ffd1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include <mmresultdialogs.hxx>
#include <mmconfigitem.hxx>
#include <mailconfigpage.hxx>
#include "mmgreetingspage.hxx"
#include <printdata.hxx>
#include <swmessdialog.hxx>
#include <cmdid.h>
#include <swtypes.hxx>
#include <view.hxx>
#include <wrtsh.hxx>
#include <docsh.hxx>
#include <IDocumentDeviceAccess.hxx>
#include <hintids.hxx>
#include <swmodule.hxx>

#include <editeng/langitem.hxx>
#include <o3tl/temporary.hxx>
#include <svl/itemset.hxx>
#include <svl/stritem.hxx>
#include <svtools/ehdl.hxx>
#include <svtools/sfxecode.hxx>
#include <vcl/stdtext.hxx>
#include <vcl/svapp.hxx>
#include <vcl/weld.hxx>
#include <sfx2/printer.hxx>
#include <sfx2/fcontnr.hxx>
#include <sfx2/viewfrm.hxx>
#include <sfx2/docfile.hxx>
#include <sfx2/docfilt.hxx>
#include <tools/urlobj.hxx>
#include <svl/urihelper.hxx>
#include <vcl/print.hxx>
#include <rtl/tencinfo.h>
#include <sal/log.hxx>

#include <unotools/tempfile.hxx>
#include <osl/file.hxx>
#include <com/sun/star/frame/XStorable.hpp>
#include <com/sun/star/sdbcx/XColumnsSupplier.hpp>
#include <com/sun/star/sdb/XColumn.hpp>
#include <com/sun/star/task/ErrorCodeIOException.hpp>
#include <dbmgr.hxx>
#include <swunohelper.hxx>
#include <shellio.hxx>
#include <svtools/htmlcfg.hxx>
#include <sfx2/event.hxx>
#include <swevent.hxx>
#include <dbui.hxx>
#include <dbui.hrc>
#include <doc.hxx>
#include <sfx2/app.hxx>
#include <strings.hrc>
#include <comphelper/string.hxx>
#include <iodetect.hxx>

using namespace svt;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;

#define MM_DOCTYPE_OOO              1
#define MM_DOCTYPE_PDF              2
#define MM_DOCTYPE_WORD             3
#define MM_DOCTYPE_HTML             4
#define MM_DOCTYPE_TEXT             5

static OUString lcl_GetExtensionForDocType(sal_uLong nDocType)
{
    OUString sExtension;
    switch( nDocType )
    {
        case MM_DOCTYPE_OOO : sExtension = "odt"; break;
        case MM_DOCTYPE_PDF : sExtension = "pdf"; break;
        case MM_DOCTYPE_WORD: sExtension = "doc"; break;
        case MM_DOCTYPE_HTML: sExtension = "html"; break;
        case MM_DOCTYPE_TEXT: sExtension = "txt"; break;
    }
    return sExtension;
}

static OUString lcl_GetColumnValueOf(const OUString& rColumn, Reference < container::XNameAccess> const & rxColAccess )
{
    OUString sRet;
    try
    {
        if (rxColAccess->hasByName(rColumn))
        {
            Any aCol = rxColAccess->getByName(rColumn);
            Reference< sdb::XColumn > xColumn;
            aCol >>= xColumn;
            if(xColumn.is())
                sRet = xColumn->getString();
        }
    }
    catch (const uno::Exception&)
    {
    }
    return sRet;
}

/**
 * Replace email server settings in rConfigItem with those set in Writer's global
 * mail merge config settings.
 */
static void lcl_UpdateEmailSettingsFromGlobalConfig(SwMailMergeConfigItem& rConfigItem)
{
    // newly created SwMailMergeConfigItem is initialized with values from (global) config
    SwMailMergeConfigItem aConfigItem;

    // take over email-related settings
    rConfigItem.SetMailDisplayName(aConfigItem.GetMailDisplayName());
    rConfigItem.SetMailAddress(aConfigItem.GetMailAddress());
    rConfigItem.SetMailReplyTo(aConfigItem.GetMailReplyTo());
    rConfigItem.SetMailReplyTo(aConfigItem.IsMailReplyTo());
    rConfigItem.SetMailServer(aConfigItem.GetMailServer());
    rConfigItem.SetMailPort(aConfigItem.GetMailPort());
    rConfigItem.SetSecureConnection(aConfigItem.IsSecureConnection());
    // authentication settings
    rConfigItem.SetAuthentication(aConfigItem.IsAuthentication());
    rConfigItem.SetSMTPAfterPOP(aConfigItem.IsSMTPAfterPOP());
    rConfigItem.SetMailUserName(aConfigItem.GetMailUserName());
    rConfigItem.SetMailPassword(aConfigItem.GetMailPassword());
    rConfigItem.SetInServerName(aConfigItem.GetInServerName());
    rConfigItem.SetInServerPort(aConfigItem.GetInServerPort());
    rConfigItem.SetInServerPOP(aConfigItem.IsInServerPOP());
    rConfigItem.SetInServerUserName(aConfigItem.GetInServerUserName());
    rConfigItem.SetInServerPassword(aConfigItem.GetInServerPassword());
}

namespace {

class SwSaveWarningBox_Impl : public SwMessageAndEditDialog
{
    DECL_LINK( ModifyHdl, weld::Entry&, void);
public:
    SwSaveWarningBox_Impl(weld::Window* pParent, const OUString& rFileName);

    OUString        GetFileName() const
    {
        return m_xEdit->get_text();
    }
};

class SwSendQueryBox_Impl : public SwMessageAndEditDialog
{
    bool            bIsEmptyAllowed;
    DECL_LINK( ModifyHdl, weld::Entry&, void);
public:
    SwSendQueryBox_Impl(weld::Window* pParent, const OString& rID,
        const OUString& rUIXMLDescription);

    void SetValue(const OUString& rSet)
    {
        m_xEdit->set_text(rSet);
        ModifyHdl(*m_xEdit);
    }

    OUString GetValue() const
    {
        return m_xEdit->get_text();
    }

    void SetIsEmptyTextAllowed(bool bSet)
    {
        bIsEmptyAllowed = bSet;
        ModifyHdl(*m_xEdit);
    }
};

}

SwSaveWarningBox_Impl::SwSaveWarningBox_Impl(weld::Window* pParent, const OUString& rFileName)
    : SwMessageAndEditDialog(pParent, "AlreadyExistsDialog",
        "modules/swriter/ui/alreadyexistsdialog.ui")
{
    m_xEdit->set_text(rFileName);
    m_xEdit->connect_changed(LINK(this, SwSaveWarningBox_Impl, ModifyHdl));

    INetURLObject aTmp(rFileName);
    m_xDialog->set_primary_text(m_xDialog->get_primary_text().replaceAll("%1", aTmp.getName(
            INetURLObject::LAST_SEGMENT, true, INetURLObject::DecodeMechanism::WithCharset)));

    ModifyHdl(*m_xEdit);
}

IMPL_LINK( SwSaveWarningBox_Impl, ModifyHdl, weld::Entry&, rEdit, void)
{
    m_xOKPB->set_sensitive(!rEdit.get_text().isEmpty());
}

SwSendQueryBox_Impl::SwSendQueryBox_Impl(weld::Window* pParent, const OString& rID,
        const OUString& rUIXMLDescription)
    : SwMessageAndEditDialog(pParent, rID, rUIXMLDescription)
    , bIsEmptyAllowed(true)
{
    m_xEdit->connect_changed(LINK(this, SwSendQueryBox_Impl, ModifyHdl));
    ModifyHdl(*m_xEdit);
}

IMPL_LINK( SwSendQueryBox_Impl, ModifyHdl, weld::Entry&, rEdit, void)
{
    m_xOKPB->set_sensitive(bIsEmptyAllowed  || !rEdit.get_text().isEmpty());
}

namespace {

class SwCopyToDialog : public SfxDialogController
{
    std::unique_ptr<weld::Entry> m_xCCED;
    std::unique_ptr<weld::Entry> m_xBCCED;

public:
    explicit SwCopyToDialog(weld::Window* pParent)
        : SfxDialogController(pParent, "modules/swriter/ui/ccdialog.ui", "CCDialog")
        , m_xCCED(m_xBuilder->weld_entry("cc"))
        , m_xBCCED(m_xBuilder->weld_entry("bcc"))
    {
    }

    OUString GetCC() const {return m_xCCED->get_text();}
    void SetCC(const OUString& rSet) {m_xCCED->set_text(rSet);}

    OUString GetBCC() const {return m_xBCCED->get_text();}
    void SetBCC(const OUString& rSet) {m_xBCCED->set_text(rSet);}
};

}

SwMMResultSaveDialog::SwMMResultSaveDialog(weld::Window* pParent)
    : SfxDialogController(pParent, "modules/swriter/ui/mmresultsavedialog.ui", "MMResultSaveDialog")
    , m_bCancelSaving(false)
    , m_xSaveAsOneRB(m_xBuilder->weld_radio_button("singlerb"))
    , m_xSaveIndividualRB(m_xBuilder->weld_radio_button("individualrb"))
    , m_xFromRB(m_xBuilder->weld_radio_button("fromrb"))
    , m_xFromNF(m_xBuilder->weld_spin_button("from"))
    , m_xToFT(m_xBuilder->weld_label("toft"))
    , m_xToNF(m_xBuilder->weld_spin_button("to"))
    , m_xOKButton(m_xBuilder->weld_button("ok"))
{
    Link<weld::ToggleButton&,void> aLink = LINK(this, SwMMResultSaveDialog, DocumentSelectionHdl_Impl);
    m_xSaveAsOneRB->connect_toggled(aLink);
    m_xSaveIndividualRB->connect_toggled(aLink);
    m_xFromRB->connect_toggled(aLink);
    // m_pSaveAsOneRB is the default, so disable m_xFromNF and m_xToNF initially.
    aLink.Call(*m_xSaveAsOneRB);
    SwView* pView = ::GetActiveView();
    const std::shared_ptr<SwMailMergeConfigItem>& xConfigItem = pView->GetMailMergeConfigItem();
    assert(xConfigItem);
    sal_Int32 nCount = xConfigItem->GetMergedDocumentCount();
    m_xFromNF->set_max(nCount);
    m_xToNF->set_max(nCount);
    m_xToNF->set_value(nCount);

    m_xOKButton->connect_clicked(LINK(this, SwMMResultSaveDialog, SaveOutputHdl_Impl));
}

SwMMResultSaveDialog::~SwMMResultSaveDialog()
{
}

SwMMResultPrintDialog::SwMMResultPrintDialog(weld::Window* pParent)
    : SfxDialogController(pParent, "modules/swriter/ui/mmresultprintdialog.ui", "MMResultPrintDialog")
    , m_xPrinterFT(m_xBuilder->weld_label("printerft"))
    , m_xPrinterLB(m_xBuilder->weld_combo_box("printers"))
    , m_xPrinterSettingsPB(m_xBuilder->weld_button("printersettings"))
    , m_xPrintAllRB(m_xBuilder->weld_radio_button("printallrb"))
    , m_xFromRB(m_xBuilder->weld_radio_button("fromrb"))
    , m_xFromNF(m_xBuilder->weld_spin_button("from"))
    , m_xToFT(m_xBuilder->weld_label("toft"))
    , m_xToNF(m_xBuilder->weld_spin_button("to"))
    , m_xOKButton(m_xBuilder->weld_button("ok"))
{
    m_xPrinterLB->make_sorted();

    m_xPrinterLB->connect_changed(LINK(this, SwMMResultPrintDialog, PrinterChangeHdl_Impl));
    m_xPrinterSettingsPB->connect_clicked(LINK(this, SwMMResultPrintDialog, PrinterSetupHdl_Impl));

    Link<weld::ToggleButton&,void> aLink = LINK(this, SwMMResultPrintDialog, DocumentSelectionHdl_Impl);
    m_xPrintAllRB->connect_toggled(aLink);
    m_xFromRB->connect_toggled(aLink);
    // m_pPrintAllRB is the default, so disable m_xFromNF and m_xToNF initially.
    aLink.Call(*m_xPrintAllRB);

    m_xOKButton->connect_clicked(LINK(this, SwMMResultPrintDialog, PrintHdl_Impl));

    FillInPrinterSettings();
}

SwMMResultPrintDialog::~SwMMResultPrintDialog()
{
}

SwMMResultEmailDialog::SwMMResultEmailDialog(weld::Window* pParent)
    : SfxDialogController(pParent, "modules/swriter/ui/mmresultemaildialog.ui", "MMResultEmailDialog")
    , m_sConfigureMail(SwResId(ST_CONFIGUREMAIL))
    , m_xMailToFT(m_xBuilder->weld_label("mailtoft"))
    , m_xMailToLB(m_xBuilder->weld_combo_box("mailto"))
    , m_xCopyToPB(m_xBuilder->weld_button("copyto"))
    , m_xSubjectFT(m_xBuilder->weld_label("subjectft"))
    , m_xSubjectED(m_xBuilder->weld_entry("subject"))
    , m_xSendAsFT(m_xBuilder->weld_label("sendasft"))
    , m_xSendAsLB(m_xBuilder->weld_combo_box("sendas"))
    , m_xSendAsPB(m_xBuilder->weld_button("sendassettings"))
    , m_xAttachmentGroup(m_xBuilder->weld_widget("attachgroup"))
    , m_xAttachmentED(m_xBuilder->weld_entry("attach"))
    , m_xSendAllRB(m_xBuilder->weld_radio_button("sendallrb"))
    , m_xFromRB(m_xBuilder->weld_radio_button("fromrb"))
    , m_xFromNF(m_xBuilder->weld_spin_button("from"))
    , m_xToFT(m_xBuilder->weld_label("toft"))
    , m_xToNF(m_xBuilder->weld_spin_button("to"))
    , m_xOKButton(m_xBuilder->weld_button("ok"))
{
    m_xCopyToPB->connect_clicked(LINK(this, SwMMResultEmailDialog, CopyToHdl_Impl));
    m_xSendAsPB->connect_clicked(LINK(this, SwMMResultEmailDialog, SendAsHdl_Impl));
    m_xSendAsLB->connect_changed(LINK(this, SwMMResultEmailDialog, SendTypeHdl_Impl));

    Link<weld::ToggleButton&,void> aLink = LINK(this, SwMMResultEmailDialog, DocumentSelectionHdl_Impl);
    m_xSendAllRB->connect_toggled(aLink);
    m_xFromRB->connect_toggled(aLink);
    // m_xSendAllRB is the default, so disable m_xFromNF and m_xToNF initially.
    aLink.Call(*m_xSendAllRB);

    m_xOKButton->connect_clicked(LINK(this, SwMMResultEmailDialog, SendDocumentsHdl_Impl));

    FillInEmailSettings();
}

SwMMResultEmailDialog::~SwMMResultEmailDialog()
{
}

void SwMMResultPrintDialog::FillInPrinterSettings()
{
    //fill printer ListBox
    SwView* pView = ::GetActiveView();
    const std::shared_ptr<SwMailMergeConfigItem>& xConfigItem = pView->GetMailMergeConfigItem();
    const std::vector<OUString>& rPrinters = Printer::GetPrinterQueues();
    unsigned int nCount = rPrinters.size();
    bool bMergePrinterExists = false;

    for (unsigned int i = 0; i < nCount; ++i)
    {
        m_xPrinterLB->append_text( rPrinters[i] );
        if( !bMergePrinterExists && rPrinters[i] == xConfigItem->GetSelectedPrinter() )
            bMergePrinterExists = true;
    }

    assert(xConfigItem);
    if(!bMergePrinterExists)
    {
        SfxPrinter* pPrinter = pView->GetWrtShell().getIDocumentDeviceAccess().getPrinter( true );
        m_xPrinterLB->set_active_text(pPrinter->GetName());
    }
    else
    {
        m_xPrinterLB->set_active_text(xConfigItem->GetSelectedPrinter());
    }
    PrinterChangeHdl_Impl(*m_xPrinterLB);

    sal_Int32 count = xConfigItem->GetMergedDocumentCount();
    m_xToNF->set_value(count);
    m_xToNF->set_max(count);
}

void SwMMResultEmailDialog::FillInEmailSettings()
{
    SwView* pView = ::GetActiveView();
    const std::shared_ptr<SwMailMergeConfigItem>& xConfigItem = pView->GetMailMergeConfigItem();
    assert(xConfigItem);

    SwView* pSourceView = xConfigItem->GetSourceView();
    OSL_ENSURE(pSourceView, "no source view exists");
    if (pSourceView)
    {
        SwDocShell* pDocShell = pSourceView->GetDocShell();
        if (pDocShell->HasName())
        {
            INetURLObject aTmp(pDocShell->GetMedium()->GetName());
            m_xAttachmentED->set_text(aTmp.getName(
                    INetURLObject::LAST_SEGMENT, true, INetURLObject::DecodeMechanism::WithCharset ));
        }
    }

    if (m_xAttachmentED->get_text().isEmpty())
    {
        OUString sAttach = "." + lcl_GetExtensionForDocType(m_xSendAsLB->get_active_id().toUInt32());
        m_xAttachmentED->set_text(sAttach);

    }

    //select first column
    uno::Reference< sdbcx::XColumnsSupplier > xColsSupp(xConfigItem->GetResultSet(), uno::UNO_QUERY);
    //get the name of the actual columns
    uno::Reference < container::XNameAccess> xColAccess = xColsSupp.is() ? xColsSupp->getColumns() : nullptr;
    uno::Sequence< OUString > aFields;
    if (xColAccess.is())
        aFields = xColAccess->getElementNames();

    // fill mail address ListBox
    assert(m_xMailToLB->get_count() == 0);
    for (const OUString& rField : std::as_const(aFields))
        m_xMailToLB->append_text(rField);

    m_xMailToLB->set_active(0);
    // then select the right one - may not be available
    const std::vector<std::pair<OUString, int>>& rHeaders = xConfigItem->GetDefaultAddressHeaders();
    OUString sEMailColumn = rHeaders[MM_PART_E_MAIL].first;
    Sequence< OUString> aAssignment = xConfigItem->GetColumnAssignment(xConfigItem->GetCurrentDBData());
    if (aAssignment.getLength() > MM_PART_E_MAIL && !aAssignment[MM_PART_E_MAIL].isEmpty())
        sEMailColumn = aAssignment[MM_PART_E_MAIL];
    m_xMailToLB->set_active_text(sEMailColumn);

    // HTML format pre-selected
    m_xSendAsLB->set_active(3);
    SendTypeHdl_Impl(*m_xSendAsLB);

}

IMPL_LINK_NOARG(SwMMResultSaveDialog, DocumentSelectionHdl_Impl, weld::ToggleButton&, void)
{
    bool bEnableFromTo = m_xFromRB->get_active();
    m_xFromNF->set_sensitive(bEnableFromTo);
    m_xToFT->set_sensitive(bEnableFromTo);
    m_xToNF->set_sensitive(bEnableFromTo);
}

IMPL_LINK_NOARG(SwMMResultPrintDialog, DocumentSelectionHdl_Impl, weld::ToggleButton&, void)
{
    bool bEnableFromTo = m_xFromRB->get_active();
    m_xFromNF->set_sensitive(bEnableFromTo);
    m_xToFT->set_sensitive(bEnableFromTo);
    m_xToNF->set_sensitive(bEnableFromTo);
}

IMPL_LINK_NOARG(SwMMResultEmailDialog, DocumentSelectionHdl_Impl, weld::ToggleButton&, void)
{
    bool bEnableFromTo = m_xFromRB->get_active();
    m_xFromNF->set_sensitive(bEnableFromTo);
    m_xToFT->set_sensitive(bEnableFromTo);
    m_xToNF->set_sensitive(bEnableFromTo);
}

IMPL_LINK_NOARG(SwMMResultEmailDialog, CopyToHdl_Impl, weld::Button&, void)
{
    SwCopyToDialog aDlg(m_xDialog.get());
    aDlg.SetCC(m_sCC );
    aDlg.SetBCC(m_sBCC);
    if (aDlg.run() == RET_OK)
    {
        m_sCC = aDlg.GetCC() ;
        m_sBCC = aDlg.GetBCC();
    }
}

namespace {

int documentStartPageNumber(SwMailMergeConfigItem* pConfigItem, int document, bool bIgnoreEmpty)
{
    SwView* pTargetView = pConfigItem->GetTargetView();
    assert( pTargetView );
    SwCursorShell& shell = pTargetView->GetWrtShell();
    const SwDocMergeInfo& info = pConfigItem->GetDocumentMergeInfo(document);
    sal_uInt16 page;
    shell.Push();
    shell.GotoMark( info.startPageInTarget );
    if (!bIgnoreEmpty)
        shell.GetPageNum(page, o3tl::temporary(sal_uInt16()));
    else
        page = shell.GetPageNumSeqNonEmpty();
    shell.Pop(SwCursorShell::PopMode::DeleteCurrent);
    return page;
}

int documentEndPageNumber(SwMailMergeConfigItem* pConfigItem, int document, bool bIgnoreEmpty)
{
    SwView* pTargetView = pConfigItem->GetTargetView();
    assert( pTargetView );
    SwWrtShell& shell = pTargetView->GetWrtShell();
    shell.Push();
    if (document < int(pConfigItem->GetMergedDocumentCount()) - 1)
    {
        // Go to the page before the starting page of the next merged document.
        const SwDocMergeInfo& info = pConfigItem->GetDocumentMergeInfo( document + 1 );
        shell.GotoMark( info.startPageInTarget );
        shell.EndPrvPg();
    }
    else
    {   // This is the last merged document, so it ends on the page at which the document ends.
        shell.SttEndDoc( false ); // go to doc end
    }
    sal_uInt16 page;
    if (!bIgnoreEmpty)
        shell.GetPageNum(page, o3tl::temporary(sal_uInt16()));
    else
        page = shell.GetPageNumSeqNonEmpty();
    shell.Pop(SwCursorShell::PopMode::DeleteCurrent);
    return page;
}

} // anonymous namespace

IMPL_LINK_NOARG(SwMMResultSaveDialog, SaveOutputHdl_Impl, weld::Button&, void)
{
    SwView* pView = ::GetActiveView();
    std::shared_ptr<SwMailMergeConfigItem> xConfigItem = pView->GetMailMergeConfigItem();
    assert(xConfigItem);
    if (!xConfigItem->GetTargetView())
        SwDBManager::PerformMailMerge(pView);

    SwView* pTargetView = xConfigItem->GetTargetView();
    assert(pTargetView);

    OUString sFilter;
    OUString sPath = SwMailMergeHelper::CallSaveAsDialog(m_xDialog.get(), sFilter);
    if (sPath.isEmpty())
    {
        // just return back to the dialog
        return;
    }

    if (m_xSaveAsOneRB->get_active())
    {
        uno::Sequence< beans::PropertyValue > aValues(1);
        beans::PropertyValue* pValues = aValues.getArray();
        pValues[0].Name = "FilterName";
        pValues[0].Value <<= sFilter;

        uno::Reference< frame::XStorable > xStore( pTargetView->GetDocShell()->GetModel(), uno::UNO_QUERY);
        ErrCode nErrorCode = ERRCODE_NONE;
        try
        {
            xStore->storeToURL( sPath, aValues );
        }
        catch (const task::ErrorCodeIOException& rErrorEx)
        {
            nErrorCode = ErrCode(rErrorEx.ErrCode);
        }
        catch (const Exception&)
        {
            nErrorCode = ERRCODE_IO_GENERAL;
        }
        if( nErrorCode != ERRCODE_NONE )
        {
            SfxErrorContext aEc(ERRCTX_SFX_SAVEASDOC, pTargetView->GetDocShell()->GetTitle());
            ErrorHandler::HandleError( nErrorCode );
        }
    }
    else
    {
        const sal_uInt32 nDocumentCount = xConfigItem->GetMergedDocumentCount();
        sal_uInt32 nBegin = 0;
        sal_uInt32 nEnd = nDocumentCount;

        if (!m_xSaveIndividualRB->get_active())
        {
            nBegin  = static_cast< sal_Int32 >(m_xFromNF->get_value() - 1);
            nEnd    = static_cast< sal_Int32 >(m_xToNF->get_value());
            if(nEnd > nDocumentCount)
                nEnd = nDocumentCount;
        }

        OUString sTargetTempURL = URIHelper::SmartRel2Abs(
            INetURLObject(), utl::TempFile::CreateTempName(),
            URIHelper::GetMaybeFileHdl());
        std::shared_ptr<const SfxFilter> pSfxFlt = SwIoSystem::GetFilterOfFormat(
                FILTER_XML,
                SwDocShell::Factory().GetFilterContainer() );

        uno::Sequence< beans::PropertyValue > aValues(1);
        beans::PropertyValue* pValues = aValues.getArray();
        pValues[0].Name = "FilterName";
        pValues[0].Value <<= pSfxFlt->GetFilterName();

        uno::Reference< frame::XStorable > xStore( pTargetView->GetDocShell()->GetModel(), uno::UNO_QUERY);
        ErrCode nErrorCode = ERRCODE_NONE;
        try
        {
            xStore->storeToURL( sTargetTempURL, aValues );
        }
        catch (const task::ErrorCodeIOException& rErrorEx)
        {
            nErrorCode = ErrCode(rErrorEx.ErrCode);
        }
        catch (const Exception&)
        {
            nErrorCode = ERRCODE_IO_GENERAL;
        }
        if( nErrorCode != ERRCODE_NONE )
        {
            SfxErrorContext aEc(ERRCTX_SFX_SAVEASDOC, pTargetView->GetDocShell()->GetTitle());
            ErrorHandler::HandleError( nErrorCode );
        }

        SwView* pSourceView = xConfigItem->GetSourceView();
        auto xSaveMonitor = std::make_shared<SaveMonitor>(m_xDialog.get());
        xSaveMonitor->m_xDocName->set_label(pSourceView->GetDocShell()->GetTitle(22));
        xSaveMonitor->m_xPrinter->set_label( INetURLObject( sPath ).getFSysPath( FSysStyle::Detect ) );
        m_bCancelSaving = false;
        weld::DialogController::runAsync(xSaveMonitor, [this, &xSaveMonitor](sal_Int32 nResult){
            if (nResult == RET_CANCEL)
                m_bCancelSaving = true;
            xSaveMonitor.reset();
        });

        for(sal_uInt32 nDoc = nBegin; nDoc < nEnd && !m_bCancelSaving; ++nDoc)
        {
            INetURLObject aURL(sPath);
            OUString sExtension = aURL.getExtension();
            if (sExtension.isEmpty())
            {
                sExtension = pSfxFlt->GetWildcard().getGlob().getToken(1, '.');
                sPath += "." + sExtension;
            }
            OUString sStat = SwResId(STR_STATSTR_LETTER) + " " + OUString::number( nDoc );
            xSaveMonitor->m_xPrintInfo->set_label(sStat);

            //now extract a document from the target document
            // the shell will be closed at the end, but it is more safe to use SfxObjectShellLock here
            SfxObjectShellLock xTempDocShell( new SwDocShell( SfxObjectCreateMode::STANDARD ) );
            xTempDocShell->DoInitNew();
            SfxViewFrame* pTempFrame = SfxViewFrame::LoadHiddenDocument( *xTempDocShell, SFX_INTERFACE_NONE );
            SwView* pTempView = static_cast<SwView*>( pTempFrame->GetViewShell() );
            pTargetView->GetWrtShell().StartAction();
            SwgReaderOption aOpt;
            aOpt.SetTextFormats( true );
            aOpt.SetFrameFormats( true );
            aOpt.SetPageDescs( true );
            aOpt.SetNumRules( true );
            aOpt.SetMerge( false );
            pTempView->GetDocShell()->LoadStylesFromFile(
                    sTargetTempURL, aOpt, true );
            pTempView->GetDocShell()->GetDoc()->ReplaceCompatibilityOptions( *pTargetView->GetDocShell()->GetDoc());
            pTempView->GetDocShell()->GetDoc()->ReplaceDefaults( *pTargetView->GetDocShell()->GetDoc());
            pTempView->GetDocShell()->GetDoc()->ReplaceDocumentProperties( *pTargetView->GetDocShell()->GetDoc(), true );

            pTargetView->GetWrtShell().PastePages(
                pTempView->GetWrtShell(), documentStartPageNumber(xConfigItem.get(), nDoc, false),
                documentEndPageNumber(xConfigItem.get(), nDoc, false));
            pTargetView->GetWrtShell().EndAction();
            //then save it
            OUString sOutPath = aURL.GetMainURL(INetURLObject::DecodeMechanism::ToIUri);
            OUString sCounter = "_" + OUString::number(nDoc + 1);
            sOutPath = sOutPath.replaceAt( sOutPath.getLength() - sExtension.getLength() - 1, 0, sCounter);

            while(true)
            {
                //time for other slots is needed
                Application::Reschedule( true );
                bool bFailed = false;
                try
                {
                    pValues[0].Value <<= sFilter;
                    uno::Reference< frame::XStorable > xTempStore( xTempDocShell->GetModel(), uno::UNO_QUERY);
                    xTempStore->storeToURL( sOutPath, aValues   );
                }
                catch (const uno::Exception&)
                {
                    bFailed = true;
                }

                if(bFailed)
                {
                    std::unique_ptr<SwSaveWarningBox_Impl> xWarning(new SwSaveWarningBox_Impl(m_xDialog.get(), sOutPath));
                    if (RET_OK == xWarning->run())
                        sOutPath = xWarning->GetFileName();
                    else
                    {
                        xTempDocShell->DoClose();
                        m_xDialog->response(RET_OK);
                        return;
                    }
                }
                else
                {
                    xTempDocShell->DoClose();
                    m_xDialog->response(RET_OK);
                    break;
                }
            }
        }
        if (xSaveMonitor)
            xSaveMonitor->response(RET_OK);
        ::osl::File::remove( sTargetTempURL );
    }

    m_xDialog->response(RET_OK);
}

IMPL_LINK(SwMMResultPrintDialog, PrinterChangeHdl_Impl, weld::ComboBox&, rBox, void)
{
    SwView* pView = ::GetActiveView();
    const std::shared_ptr<SwMailMergeConfigItem>& xConfigItem = pView->GetMailMergeConfigItem();
    assert(xConfigItem);
    if (rBox.get_active() != -1)
    {
        const QueueInfo* pInfo = Printer::GetQueueInfo( rBox.get_active_text(), false );

        if( pInfo )
        {
            if ( !m_pTempPrinter )
            {
                m_pTempPrinter = VclPtr<Printer>::Create( *pInfo );
            }
            else
            {
                if( (m_pTempPrinter->GetName() != pInfo->GetPrinterName()) ||
                     (m_pTempPrinter->GetDriverName() != pInfo->GetDriver()) )
                {
                    m_pTempPrinter.disposeAndClear();
                    m_pTempPrinter = VclPtr<Printer>::Create( *pInfo );
                }
            }
        }
        else if( ! m_pTempPrinter )
            m_pTempPrinter = VclPtr<Printer>::Create();

        m_xPrinterSettingsPB->set_sensitive(m_pTempPrinter->HasSupport(PrinterSupport::SetupDialog));
    }
    else
        m_xPrinterSettingsPB->set_sensitive(false);

    xConfigItem->SetSelectedPrinter(rBox.get_active_text());
}

IMPL_LINK_NOARG(SwMMResultPrintDialog, PrintHdl_Impl, weld::Button&, void)
{
    SwView* pView = ::GetActiveView();
    std::shared_ptr<SwMailMergeConfigItem> xConfigItem = pView->GetMailMergeConfigItem();
    assert(xConfigItem);
    if(!xConfigItem->GetTargetView())
        SwDBManager::PerformMailMerge(pView);

    SwView* pTargetView = xConfigItem->GetTargetView();
    assert(pTargetView);

    const sal_uInt32 nDocumentCount = xConfigItem->GetMergedDocumentCount();
    sal_uInt32 nBegin = 0;
    sal_uInt32 nEnd = nDocumentCount;

    if (!m_xPrintAllRB->get_active())
    {
        nBegin  = m_xFromNF->get_value() - 1;
        nEnd    = m_xToNF->get_value();
        if(nEnd > nDocumentCount)
            nEnd = nDocumentCount;
    }

    // If we skip autoinserted blanks, then the page numbers used in the print range string
    // refer to the non-blank pages as they appear in the document (see tdf#89708).
    const bool bIgnoreEmptyPages =
            !pTargetView->GetDocShell()->GetDoc()->getIDocumentDeviceAccess().getPrintData().IsPrintEmptyPages();
    const int nStartPage = documentStartPageNumber(xConfigItem.get(), nBegin, bIgnoreEmptyPages);
    const int nEndPage = documentEndPageNumber(xConfigItem.get(), nEnd - 1, bIgnoreEmptyPages);

    const OUString sPages(OUString::number(nStartPage) + "-" + OUString::number(nEndPage));

    pTargetView->SetMailMergeConfigItem(xConfigItem);
    if(m_pTempPrinter)
    {
        SfxPrinter *const pDocumentPrinter = pTargetView->GetWrtShell()
            .getIDocumentDeviceAccess().getPrinter(true);
        pDocumentPrinter->SetPrinterProps(m_pTempPrinter);
        // this should be able to handle setting its own printer
        pTargetView->SetPrinter(pDocumentPrinter);
    }

    SfxObjectShell* pObjSh = pTargetView->GetViewFrame()->GetObjectShell();
    SfxGetpApp()->NotifyEvent(SfxEventHint(SfxEventHintId::SwMailMerge, SwDocShell::GetEventName(STR_SW_EVENT_MAIL_MERGE), pObjSh));

    uno::Sequence < beans::PropertyValue > aProps( 2 );
    aProps[0]. Name = "MonitorVisible";
    aProps[0].Value <<= true;
    aProps[1]. Name = "Pages";
    aProps[1]. Value <<= sPages;

    pTargetView->ExecPrint( aProps, false, true );
    SfxGetpApp()->NotifyEvent(SfxEventHint(SfxEventHintId::SwMailMergeEnd, SwDocShell::GetEventName(STR_SW_EVENT_MAIL_MERGE_END), pObjSh));

    m_xDialog->response(RET_OK);
}

IMPL_LINK_NOARG(SwMMResultPrintDialog, PrinterSetupHdl_Impl, weld::Button&, void)
{
    if (m_pTempPrinter)
        m_pTempPrinter->Setup(m_xDialog.get());
}

IMPL_LINK(SwMMResultEmailDialog, SendTypeHdl_Impl, weld::ComboBox&, rBox, void)
{
    auto nDocType = rBox.get_active_id().toUInt32();
    bool bEnable = MM_DOCTYPE_HTML != nDocType && MM_DOCTYPE_TEXT != nDocType;
    m_xSendAsPB->set_sensitive(bEnable);
    m_xAttachmentGroup->set_sensitive(bEnable);
    if(bEnable)
    {
        //add the correct extension
        OUString sAttach(m_xAttachmentED->get_text());
        //do nothing if the user has removed the name - the warning will come early enough
        if (!sAttach.isEmpty())
        {
            sal_Int32 nTokenCount = comphelper::string::getTokenCount(sAttach, '.');
            if( 2 > nTokenCount)
            {
                sAttach += ".";
                ++nTokenCount;
            }
            sAttach = comphelper::string::setToken(sAttach, nTokenCount - 1, '.', lcl_GetExtensionForDocType( nDocType ));
            m_xAttachmentED->set_text(sAttach);
        }
    }
}

IMPL_LINK_NOARG(SwMMResultEmailDialog, SendAsHdl_Impl, weld::Button&, void)
{
    SwMailBodyDialog aDlg(m_xDialog.get());
    aDlg.SetBody(m_sBody);
    if (RET_OK == aDlg.run())
    {
        m_sBody = aDlg.GetBody();
    }
}

// Send documents as e-mail
IMPL_LINK_NOARG(SwMMResultEmailDialog, SendDocumentsHdl_Impl, weld::Button&, void)
{
    SwView* pView = ::GetActiveView();
    std::shared_ptr<SwMailMergeConfigItem> xConfigItem = pView->GetMailMergeConfigItem();
    assert(xConfigItem);
    if (!xConfigItem->GetTargetView())
        SwDBManager::PerformMailMerge(pView);

    //get the composed document
    SwView* pTargetView = xConfigItem->GetTargetView();
    SAL_WARN_IF(!pTargetView, "sw.ui", "No TargetView in SwMailMergeConfigItem");

    if (xConfigItem->GetMailServer().isEmpty() ||
            !SwMailMergeHelper::CheckMailAddress(xConfigItem->GetMailAddress()) )
    {
        std::unique_ptr<weld::MessageDialog> xQueryBox(Application::CreateMessageDialog(m_xDialog.get(),
                                                       VclMessageType::Question, VclButtonsType::YesNo,
                                                       m_sConfigureMail));
        xQueryBox->add_button(GetStandardText(StandardButtonType::Cancel), RET_CANCEL);
        sal_uInt16 nRet = xQueryBox->run();
        if (RET_YES == nRet )
        {
            SwView* pConfigView = pTargetView ? pTargetView : pView;
            SfxAllItemSet aSet(pConfigView->GetPool());
            SwMailConfigDlg aDlg(m_xDialog.get(), aSet);
            nRet = aDlg.run();
        }

        if(nRet != RET_OK && nRet != RET_YES)
            return; // back to the dialog

        // SwMailConfigDlg writes mail merge email settings only to (global) config,
        // so copy them to the existing config item
        lcl_UpdateEmailSettingsFromGlobalConfig(*xConfigItem);
    }
    //add the documents
    const sal_uInt32 nDocumentCount = xConfigItem->GetMergedDocumentCount();
    sal_uInt32 nBegin = 0;
    sal_uInt32 nEnd = nDocumentCount;
    if (!m_xSendAllRB->get_active())
    {
        nBegin  = static_cast< sal_Int32 >(m_xFromNF->get_value() - 1);
        nEnd    = static_cast< sal_Int32 >(m_xToNF->get_value());
        if(nEnd > nDocumentCount)
            nEnd = nDocumentCount;
    }
    bool bAsBody = false;
    rtl_TextEncoding eEncoding = ::osl_getThreadTextEncoding();
    SfxFilterContainer* pFilterContainer = SwDocShell::Factory().GetFilterContainer();
    std::shared_ptr<const SfxFilter> pSfxFlt;
    auto nDocType = m_xSendAsLB->get_active_id().toUInt32();
    OUString sExtension = lcl_GetExtensionForDocType(nDocType);
    switch( nDocType )
    {
        case MM_DOCTYPE_OOO:
        {
            //Make sure we don't pick e.g. the flat xml filter
            //for this format
            pSfxFlt = pFilterContainer->GetFilter4FilterName(
                "writer8",
                SfxFilterFlags::EXPORT);
        }
        break;
        case MM_DOCTYPE_PDF:
        {
            pSfxFlt = pFilterContainer->GetFilter4FilterName(
                "writer_pdf_Export",
                SfxFilterFlags::EXPORT);
        }
        break;
        case MM_DOCTYPE_WORD:
        {
            //the method SwIOSystemGetFilterOfFormat( ) returns the template filter
            //because it uses the same user data :-(
            SfxFilterMatcher aMatcher( pFilterContainer->GetName() );
            SfxFilterMatcherIter aIter( aMatcher );
            std::shared_ptr<const SfxFilter> pFilter = aIter.First();
            while ( pFilter )
            {
                if( pFilter->GetUserData() == FILTER_WW8 && pFilter->CanExport() )
                {
                    pSfxFlt = pFilter;
                    break;
                }
                pFilter = aIter.Next();
            }

        }
        break;
        case MM_DOCTYPE_HTML:
        {
            bAsBody = true;
            SvxHtmlOptions& rHtmlOptions = SvxHtmlOptions::Get();
            eEncoding = rHtmlOptions.GetTextEncoding();
        }
        break;
        case MM_DOCTYPE_TEXT:
        {
            bAsBody = true;
            pSfxFlt = pFilterContainer->GetFilter4FilterName(
                "Text (encoded)", SfxFilterFlags::EXPORT);
        }
        break;
    }
    if(!pSfxFlt)
        pSfxFlt = pFilterContainer->GetFilter4Extension(sExtension, SfxFilterFlags::EXPORT);

    if(!pSfxFlt)
    {
        m_xDialog->response(RET_OK);
        return;
    }
    OUString sMimeType = pSfxFlt->GetMimeType();

    if (m_xSubjectED->get_text().isEmpty())
    {
        std::unique_ptr<SwSendQueryBox_Impl> xQuery(new SwSendQueryBox_Impl(m_xDialog.get(), "SubjectDialog",
                                                         "modules/swriter/ui/subjectdialog.ui"));
        xQuery->SetIsEmptyTextAllowed(true);
        xQuery->SetValue("");
        if(RET_OK == xQuery->run())
        {
            if (!xQuery->GetValue().isEmpty())
                m_xSubjectED->set_text(xQuery->GetValue());
        }
        else
            return; // back to the dialog
    }
    if(!bAsBody && m_xAttachmentED->get_text().isEmpty())
    {
        std::unique_ptr<SwSendQueryBox_Impl> xQuery(new SwSendQueryBox_Impl(m_xDialog.get(), "AttachNameDialog",
                                                         "modules/swriter/ui/attachnamedialog.ui"));
        xQuery->SetIsEmptyTextAllowed(false);
        if (RET_OK == xQuery->run())
        {
            OUString sAttach(xQuery->GetValue());
            sal_Int32 nTokenCount = comphelper::string::getTokenCount(sAttach, '.');
            if (2 > nTokenCount)
            {
                sAttach += ".";
                ++nTokenCount;
            }
            sAttach = comphelper::string::setToken(sAttach, nTokenCount - 1, '.', lcl_GetExtensionForDocType(
                                                   m_xSendAsLB->get_active_id().toUInt32()));
            m_xAttachmentED->set_text(sAttach);
        }
        else
            return; // back to the dialog
    }
    OUString sEMailColumn = m_xMailToLB->get_active_text();
    OSL_ENSURE( !sEMailColumn.isEmpty(), "No email column selected");
    Reference< sdbcx::XColumnsSupplier > xColsSupp( xConfigItem->GetResultSet(), UNO_QUERY);
    Reference < container::XNameAccess> xColAccess = xColsSupp.is() ? xColsSupp->getColumns() : nullptr;
    if(sEMailColumn.isEmpty() || !xColAccess.is() || !xColAccess->hasByName(sEMailColumn))
    {
        m_xDialog->response(RET_OK);
        return;
    }

    OUString sFilterOptions;
    if(MM_DOCTYPE_TEXT == nDocType)
    {
        SwAsciiOptions aOpt;
        sal_uInt16 nAppScriptType = SvtLanguageOptions::GetI18NScriptTypeOfLanguage( GetAppLanguage() );
        sal_uInt16 nWhich = GetWhichOfScript( RES_CHRATR_LANGUAGE, nAppScriptType);
        aOpt.SetLanguage( static_cast<const SvxLanguageItem&>(pTargetView->GetWrtShell().
                            GetDefault( nWhich )).GetLanguage());
        aOpt.SetParaFlags( LINEEND_CR );
        aOpt.WriteUserData( sFilterOptions );
    }
    else if(MM_DOCTYPE_HTML == nDocType)
    {
        sFilterOptions = "EmbedImages";
    }
    OUString sTargetTempURL = URIHelper::SmartRel2Abs(
        INetURLObject(), utl::TempFile::CreateTempName(),
        URIHelper::GetMaybeFileHdl());
    std::shared_ptr<const SfxFilter> pTargetSfxFlt = SwIoSystem::GetFilterOfFormat(
            FILTER_XML,
            SwDocShell::Factory().GetFilterContainer() );

    uno::Sequence< beans::PropertyValue > aValues(1);
    beans::PropertyValue* pValues = aValues.getArray();
    pValues[0].Name = "FilterName";
    pValues[0].Value <<= pTargetSfxFlt->GetFilterName();

    uno::Reference< frame::XStorable > xStore( pTargetView->GetDocShell()->GetModel(), uno::UNO_QUERY);
    xStore->storeToURL( sTargetTempURL, aValues   );

    //create the send dialog
    vcl::Window* pParent = Application::GetDefDialogParent();
    std::shared_ptr<SwSendMailDialog> xDlg = std::make_shared<SwSendMailDialog>(pParent ? pParent->GetFrameWeld() : nullptr, *xConfigItem);

    xDlg->StartSend(nEnd - nBegin);
    weld::DialogController::runAsync(xDlg, [](sal_Int32 /*nResult*/){});

    //help to force painting the dialog
    //TODO/CLEANUP
    //predetermined breaking point
    Application::Reschedule( true );
    m_xDialog->response(RET_OK);
    for(sal_uInt32 nDoc = nBegin; nDoc < nEnd; ++nDoc)
    {
        SwDocMergeInfo& rInfo = xConfigItem->GetDocumentMergeInfo(nDoc);

        //now extract a document from the target document
        // the shell will be closed at the end, but it is more safe to use SfxObjectShellLock here
        SfxObjectShellLock xTempDocShell( new SwDocShell( SfxObjectCreateMode::STANDARD ) );
        xTempDocShell->DoInitNew();
        SfxViewFrame* pTempFrame = SfxViewFrame::LoadHiddenDocument( *xTempDocShell, SFX_INTERFACE_NONE );
        SwView* pTempView = static_cast<SwView*>( pTempFrame->GetViewShell() );
        pTargetView->GetWrtShell().StartAction();
        SwgReaderOption aOpt;
        aOpt.SetTextFormats( true );
        aOpt.SetFrameFormats( true );
        aOpt.SetPageDescs( true );
        aOpt.SetNumRules( true );
        aOpt.SetMerge( false );
        pTempView->GetDocShell()->LoadStylesFromFile(
                sTargetTempURL, aOpt, true );
        pTempView->GetDocShell()->GetDoc()->ReplaceCompatibilityOptions( *pTargetView->GetDocShell()->GetDoc());
        pTempView->GetDocShell()->GetDoc()->ReplaceDefaults( *pTargetView->GetDocShell()->GetDoc());
        pTempView->GetDocShell()->GetDoc()->ReplaceDocumentProperties( *pTargetView->GetDocShell()->GetDoc(), true );
        pTargetView->GetWrtShell().PastePages(
            pTempView->GetWrtShell(), documentStartPageNumber(xConfigItem.get(), nDoc, false),
            documentEndPageNumber(xConfigItem.get(), nDoc, false));
        pTargetView->GetWrtShell().EndAction();

        //then save it
        SfxStringItem aName(SID_FILE_NAME,
                URIHelper::SmartRel2Abs(
                    INetURLObject(), utl::TempFile::CreateTempName(),
                    URIHelper::GetMaybeFileHdl()) );

        {
            bool withFilterOptions = MM_DOCTYPE_TEXT == nDocType || MM_DOCTYPE_HTML == nDocType;
            uno::Sequence< beans::PropertyValue > aFilterValues(withFilterOptions ? 2 : 1);
            beans::PropertyValue* pFilterValues = aFilterValues.getArray();
            pFilterValues[0].Name = "FilterName";
            pFilterValues[0].Value <<= pSfxFlt->GetFilterName();
            if(withFilterOptions)
            {
                pFilterValues[1].Name = "FilterOptions";
                pFilterValues[1].Value <<= sFilterOptions;
            }

            uno::Reference< frame::XStorable > xTempStore( pTempView->GetDocShell()->GetModel(), uno::UNO_QUERY);
            xTempStore->storeToURL( aName.GetValue(), aFilterValues );
        }
        xTempDocShell->DoClose();

        sal_Int32 nTarget = xConfigItem->MoveResultSet(rInfo.nDBRow);
        OSL_ENSURE( nTarget == rInfo.nDBRow, "row of current document could not be selected");
        OSL_ENSURE( !sEMailColumn.isEmpty(), "No email column selected");
        OUString sEMail = lcl_GetColumnValueOf(sEMailColumn, xColAccess);
        SwMailDescriptor aDesc;
        aDesc.sEMail = sEMail;
        OUStringBuffer sBody;
        if(bAsBody)
        {
            {
                //read in the temporary file and use it as mail body
                SfxMedium aMedium( aName.GetValue(),    StreamMode::READ);
                SvStream* pInStream = aMedium.GetInStream();
                if(pInStream)
                    pInStream->SetStreamCharSet( eEncoding );
                else
                {
                    OSL_FAIL("no output file created?");
                    continue;
                }
                OString sLine;
                bool bDone = pInStream->ReadLine( sLine );
                while ( bDone )
                {
                    sBody.append( OStringToOUString(sLine, eEncoding) );
                    sBody.append("\n");
                    bDone = pInStream->ReadLine( sLine );
                }
            }
            //remove the temporary file
            SWUnoHelper::UCB_DeleteFile( aName.GetValue() );
        }
        else
        {
            sBody = m_sBody;
            aDesc.sAttachmentURL = aName.GetValue();
            OUString sAttachment(m_xAttachmentED->get_text());
            sal_Int32 nTokenCount = comphelper::string::getTokenCount(sAttachment, '.');
            if (2 > nTokenCount)
            {
                sAttachment += ".";
                sAttachment = comphelper::string::setToken(sAttachment, nTokenCount, '.', sExtension);
            }
            else if (sAttachment.getToken( nTokenCount - 1, '.') != sExtension)
                sAttachment += sExtension;
            aDesc.sAttachmentName = sAttachment;
            aDesc.sMimeType = sMimeType;

            if (xConfigItem->IsGreetingLine(true))
            {
                OUString sNameColumn = xConfigItem->GetAssignedColumn(MM_PART_LASTNAME);
                OUString sName = lcl_GetColumnValueOf(sNameColumn, xColAccess);
                OUString sGreeting;
                if(!sName.isEmpty() && xConfigItem->IsIndividualGreeting(true))
                {
                    OUString sGenderColumn = xConfigItem->GetAssignedColumn(MM_PART_GENDER);
                    const OUString& sFemaleValue = xConfigItem->GetFemaleGenderValue();
                    OUString sGenderValue = lcl_GetColumnValueOf(sGenderColumn, xColAccess);
                    SwMailMergeConfigItem::Gender eGenderType = sGenderValue == sFemaleValue ?
                        SwMailMergeConfigItem::FEMALE :
                        SwMailMergeConfigItem::MALE;

                    sGreeting = SwAddressPreview::FillData(
                        xConfigItem->GetGreetings(eGenderType)
                        [xConfigItem->GetCurrentGreeting(eGenderType)],
                            *xConfigItem);
                }
                else
                {
                    sGreeting =
                        xConfigItem->GetGreetings(SwMailMergeConfigItem::NEUTRAL)
                        [xConfigItem->GetCurrentGreeting(SwMailMergeConfigItem::NEUTRAL)];

                }
                sGreeting += "\n";
                sBody.insert(0, sGreeting);
            }
        }
        aDesc.sBodyContent = sBody.makeStringAndClear();
        if(MM_DOCTYPE_HTML == nDocType)
        {
            aDesc.sBodyMimeType = "text/html; charset=" +
                OUString::createFromAscii(rtl_getBestMimeCharsetFromTextEncoding( eEncoding ));
        }
        else
            aDesc.sBodyMimeType = "text/plain; charset=UTF-8; format=flowed";

        aDesc.sSubject = m_xSubjectED->get_text();
        aDesc.sCC = m_sCC;
        aDesc.sBCC = m_sBCC;
        xDlg->AddDocument( aDesc );
        //help to force painting the dialog
        Application::Reschedule( true );
        //stop creating of data when dialog has been closed
        if (!xDlg->getDialog()->get_visible())
        {
            break;
        }
    }
    xDlg->EnableDestruction();
    ::osl::File::remove( sTargetTempURL );
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */