Coverage Report

Created: 2026-09-28 10:59

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libreoffice/sfx2/source/doc/guisaveas.cxx
Line
Count
Source
1
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2
/*
3
 * This file is part of the LibreOffice project.
4
 *
5
 * This Source Code Form is subject to the terms of the Mozilla Public
6
 * License, v. 2.0. If a copy of the MPL was not distributed with this
7
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
8
 *
9
 * This file incorporates work covered by the following license notice:
10
 *
11
 *   Licensed to the Apache Software Foundation (ASF) under one or more
12
 *   contributor license agreements. See the NOTICE file distributed
13
 *   with this work for additional information regarding copyright
14
 *   ownership. The ASF licenses this file to you under the Apache
15
 *   License, Version 2.0 (the "License"); you may not use this file
16
 *   except in compliance with the License. You may obtain a copy of
17
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
18
 */
19
#include <config_gpgme.h>
20
#if HAVE_FEATURE_GPGME
21
#include <com/sun/star/xml/crypto/GPGSEInitializer.hpp>
22
#include <com/sun/star/xml/crypto/SEInitializer.hpp>
23
#include <com/sun/star/xml/crypto/XXMLSecurityContext.hpp>
24
#endif
25
#include <com/sun/star/security/DocumentDigitalSignatures.hpp>
26
#include <com/sun/star/security/XCertificate.hpp>
27
28
#include <com/sun/star/ui/dialogs/XExecutableDialog.hpp>
29
#include <com/sun/star/ui/dialogs/XAsynchronousExecutableDialog.hpp>
30
#include <com/sun/star/ui/dialogs/XFilePicker3.hpp>
31
#include <com/sun/star/ui/dialogs/XFilePickerControlAccess.hpp>
32
#include <com/sun/star/ui/dialogs/CommonFilePickerElementIds.hpp>
33
#include <com/sun/star/ui/dialogs/ExtendedFilePickerElementIds.hpp>
34
#include <com/sun/star/ui/dialogs/TemplateDescription.hpp>
35
#include <com/sun/star/view/XSelectionSupplier.hpp>
36
#include <com/sun/star/beans/PropertyExistException.hpp>
37
#include <com/sun/star/beans/XPropertyAccess.hpp>
38
#include <com/sun/star/beans/XPropertySet.hpp>
39
#include <com/sun/star/beans/XPropertyContainer.hpp>
40
#include <com/sun/star/beans/PropertyAttribute.hpp>
41
#include <com/sun/star/document/XExporter.hpp>
42
#include <com/sun/star/document/XDocumentPropertiesSupplier.hpp>
43
#include <com/sun/star/document/XDocumentProperties.hpp>
44
#include <com/sun/star/task/ErrorCodeIOException.hpp>
45
#include <com/sun/star/task/InteractionHandler.hpp>
46
#include <com/sun/star/util/URLTransformer.hpp>
47
#include <com/sun/star/util/XURLTransformer.hpp>
48
#include <com/sun/star/frame/ModuleManager.hpp>
49
#include <com/sun/star/frame/XStorable.hpp>
50
#include <com/sun/star/frame/XStorable2.hpp>
51
#include <com/sun/star/frame/XDispatchProvider.hpp>
52
#include <com/sun/star/frame/XDispatch.hpp>
53
#include <com/sun/star/frame/XTitle.hpp>
54
#include <com/sun/star/util/XModifiable.hpp>
55
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
56
57
#include <com/sun/star/util/XCloneable.hpp>
58
59
#include <guisaveas.hxx>
60
61
#include <sal/log.hxx>
62
#include <svl/itemset.hxx>
63
#include <svl/eitem.hxx>
64
#include <tools/debug.hxx>
65
#include <comphelper/diagnose_ex.hxx>
66
#include <comphelper/documentconstants.hxx>
67
#include <comphelper/namedvaluecollection.hxx>
68
#include <tools/urlobj.hxx>
69
#include <tools/json_writer.hxx>
70
#include <comphelper/processfactory.hxx>
71
#include <comphelper/propertysequence.hxx>
72
#include <comphelper/propertyvalue.hxx>
73
#include <comphelper/sequenceashashmap.hxx>
74
#include <comphelper/mimeconfighelper.hxx>
75
#include <comphelper/lok.hxx>
76
#include <comphelper/xmlsechelper.hxx>
77
#include <LibreOfficeKit/LibreOfficeKitEnums.h>
78
#include <utility>
79
#include <vcl/svapp.hxx>
80
#include <vcl/vclenum.hxx>
81
#include <vcl/weld/MessageDialog.hxx>
82
#include <o3tl/char16_t2wchar_t.hxx>
83
#include <unotools/tempfile.hxx>
84
#include <unotools/useroptions.hxx>
85
86
#include <sfx2/docfile.hxx>
87
#include <sfx2/objsh.hxx>
88
#include <sfx2/sfxsids.hrc>
89
#include <sfx2/strings.hrc>
90
#include <sfx2/sfxresid.hxx>
91
#include <sfx2/filedlghelper.hxx>
92
#include <sfx2/app.hxx>
93
#include <sfx2/sfxuno.hxx>
94
#include <sfx2/viewsh.hxx>
95
#include <sfx2/bindings.hxx>
96
97
#include <memory>
98
#include <string_view>
99
100
#include <officecfg/Office/Common.hxx>
101
102
#include <vcl/FilterConfigItem.hxx>
103
#include <com/sun/star/system/SystemShellExecute.hpp>
104
#include <com/sun/star/system/SystemShellExecuteFlags.hpp>
105
106
#include <osl/file.hxx>
107
#include <svl/cryptosign.hxx>
108
109
#include <svtools/confirmationdlg.hxx>
110
111
#ifdef _WIN32
112
#include <Shlobj.h>
113
#ifdef GetTempPath
114
#undef GetTempPath
115
#endif
116
#endif
117
118
// flags that specify requested operation
119
0
#define EXPORT_REQUESTED            1
120
0
#define PDFEXPORT_REQUESTED         2
121
0
#define PDFDIRECTEXPORT_REQUESTED   4
122
0
#define WIDEEXPORT_REQUESTED        8
123
0
#define SAVE_REQUESTED              16
124
0
#define SAVEAS_REQUESTED            32
125
0
#define SAVEACOPY_REQUESTED         64
126
0
#define EPUBEXPORT_REQUESTED       128
127
0
#define EPUBDIRECTEXPORT_REQUESTED 256
128
0
#define SAVEASREMOTE_REQUESTED      -1
129
130
// possible statuses of save operation
131
0
#define STATUS_NO_ACTION            0
132
0
#define STATUS_SAVE                 1
133
0
#define STATUS_SAVEAS               2
134
0
#define STATUS_SAVEAS_STANDARDNAME  3
135
136
constexpr OUString aFilterNameString = u"FilterName"_ustr;
137
constexpr OUString aFilterOptionsString = u"FilterOptions"_ustr;
138
constexpr OUString aFilterDataString = u"FilterData"_ustr;
139
140
using namespace ::com::sun::star;
141
using namespace css::system;
142
143
namespace {
144
145
sal_uInt16 getSlotIDFromMode( sal_Int16 nStoreMode )
146
0
{
147
    // This is a temporary hardcoded solution must be removed when
148
    // dialogs do not need parameters in SidSet representation any more
149
150
0
    sal_uInt16 nResult = 0;
151
0
    if ( nStoreMode == EXPORT_REQUESTED || nStoreMode == ( EXPORT_REQUESTED | SAVEACOPY_REQUESTED | WIDEEXPORT_REQUESTED ) )
152
0
        nResult = SID_EXPORTDOC;
153
0
    else if ( nStoreMode == ( EXPORT_REQUESTED | PDFEXPORT_REQUESTED ) )
154
0
        nResult = SID_EXPORTDOCASPDF;
155
0
    else if ( nStoreMode == ( EXPORT_REQUESTED | EPUBEXPORT_REQUESTED ) )
156
0
        nResult = SID_EXPORTDOCASEPUB;
157
0
    else if ( nStoreMode == ( EXPORT_REQUESTED | PDFEXPORT_REQUESTED | PDFDIRECTEXPORT_REQUESTED ) )
158
0
        nResult = SID_DIRECTEXPORTDOCASPDF;
159
0
    else if ( nStoreMode == ( EXPORT_REQUESTED | EPUBEXPORT_REQUESTED | EPUBDIRECTEXPORT_REQUESTED ) )
160
0
        nResult = SID_DIRECTEXPORTDOCASEPUB;
161
0
    else if ( nStoreMode == SAVEAS_REQUESTED || nStoreMode == ( EXPORT_REQUESTED | WIDEEXPORT_REQUESTED ) )
162
0
        nResult = SID_SAVEASDOC;
163
0
    else if ( nStoreMode == SAVEASREMOTE_REQUESTED )
164
0
        nResult = SID_SAVEASREMOTE;
165
0
    else {
166
0
        SAL_WARN( "sfx.doc", "Unacceptable slot name is provided!" );
167
0
    }
168
169
0
    return nResult;
170
0
}
171
172
173
sal_Int16 getStoreModeFromSlotName( std::u16string_view aSlotName )
174
0
{
175
0
    sal_Int16 nResult = 0;
176
0
    if ( aSlotName == u"ExportTo" )
177
0
        nResult = EXPORT_REQUESTED;
178
0
    else if ( aSlotName == u"ExportToPDF" )
179
0
        nResult = EXPORT_REQUESTED | PDFEXPORT_REQUESTED;
180
0
    else if ( aSlotName == u"ExportDirectToPDF" )
181
0
        nResult = EXPORT_REQUESTED | PDFEXPORT_REQUESTED | PDFDIRECTEXPORT_REQUESTED;
182
0
    else if ( aSlotName == u"ExportToEPUB" )
183
0
        nResult = EXPORT_REQUESTED | EPUBEXPORT_REQUESTED;
184
0
    else if ( aSlotName == u"ExportDirectToEPUB" )
185
0
        nResult = EXPORT_REQUESTED | EPUBEXPORT_REQUESTED | EPUBDIRECTEXPORT_REQUESTED;
186
0
    else if ( aSlotName == u"Save" )
187
0
        nResult = SAVE_REQUESTED;
188
0
    else if ( aSlotName == u"SaveAs" )
189
0
        nResult = SAVEAS_REQUESTED;
190
0
    else if ( aSlotName == u"SaveAsRemote" )
191
0
        nResult = SAVEASREMOTE_REQUESTED;
192
0
    else
193
0
        throw task::ErrorCodeIOException(
194
0
            (OUString::Concat("getStoreModeFromSlotName(\"") + aSlotName
195
0
             + "): ERRCODE_IO_INVALIDPARAMETER"),
196
0
            uno::Reference< uno::XInterface >(), sal_uInt32(ERRCODE_IO_INVALIDPARAMETER) );
197
198
0
    return nResult;
199
0
}
200
201
202
SfxFilterFlags getMustFlags( sal_Int16 nStoreMode )
203
0
{
204
0
    return ( SfxFilterFlags::EXPORT
205
0
            | ( ( ( nStoreMode & EXPORT_REQUESTED ) && !( nStoreMode & WIDEEXPORT_REQUESTED ) ) ? SfxFilterFlags::NONE : SfxFilterFlags::IMPORT ) );
206
0
}
207
208
209
SfxFilterFlags getDontFlags( sal_Int16 nStoreMode )
210
0
{
211
0
    return ( SfxFilterFlags::INTERNAL
212
0
            | SfxFilterFlags::NOTINFILEDLG
213
0
            | ( ( ( nStoreMode & EXPORT_REQUESTED ) && !( nStoreMode & WIDEEXPORT_REQUESTED ) ) ? SfxFilterFlags::IMPORT : SfxFilterFlags::NONE ) );
214
0
}
215
216
217
218
219
class DocumentSettingsGuard
220
{
221
    uno::Reference< beans::XPropertySet > m_xDocumentSettings;
222
    bool m_bPreserveReadOnly;
223
    bool m_bReadOnlySupported;
224
225
    bool m_bRestoreSettings;
226
public:
227
    DocumentSettingsGuard( const uno::Reference< frame::XModel2 >& xModel, bool bReadOnly, bool bRestore )
228
0
    : m_bPreserveReadOnly( false )
229
0
    , m_bReadOnlySupported( false )
230
0
    , m_bRestoreSettings( bRestore )
231
0
    {
232
0
        try
233
0
        {
234
0
            uno::Reference< lang::XMultiServiceFactory > xDocSettingsSupplier( xModel, uno::UNO_QUERY );
235
0
            if (xDocSettingsSupplier)
236
0
            {
237
0
                m_xDocumentSettings.set(
238
0
                    xDocSettingsSupplier->createInstance( u"com.sun.star.document.Settings"_ustr ),
239
0
                    uno::UNO_QUERY );
240
0
                if (m_xDocumentSettings)
241
0
                {
242
0
                    OUString aLoadReadonlyString( u"LoadReadonly"_ustr );
243
0
                    m_xDocumentSettings->getPropertyValue( aLoadReadonlyString ) >>= m_bPreserveReadOnly;
244
0
                    m_xDocumentSettings->setPropertyValue( aLoadReadonlyString, uno::Any( bReadOnly ) );
245
0
                    m_bReadOnlySupported = true;
246
0
                }
247
0
            }
248
0
        }
249
0
        catch( const uno::Exception& )
250
0
        {}
251
252
0
        if ( bReadOnly && !m_bReadOnlySupported )
253
0
            throw uno::RuntimeException(); // the user could provide the data, so it must be stored
254
0
    }
255
256
    ~DocumentSettingsGuard()
257
0
    {
258
0
        if ( m_bRestoreSettings )
259
0
        {
260
0
            try
261
0
            {
262
0
                if ( m_bReadOnlySupported )
263
0
                    m_xDocumentSettings->setPropertyValue( u"LoadReadonly"_ustr, uno::Any( m_bPreserveReadOnly ) );
264
0
            }
265
0
            catch( const uno::Exception& )
266
0
            {
267
0
                TOOLS_WARN_EXCEPTION( "sfx.doc", "" );
268
0
            }
269
0
        }
270
0
    }
271
};
272
} // anonymous namespace
273
274
275
276
class ModelData_Impl
277
{
278
    SfxStoringHelper* m_pOwner;
279
    uno::Reference< frame::XModel2 > m_xModel;
280
    uno::Reference< frame::XStorable > m_xStorable;
281
    uno::Reference< frame::XStorable2 > m_xStorable2;
282
283
    OUString m_aModuleName;
284
    std::unique_ptr<::comphelper::SequenceAsHashMap> m_pDocumentPropsHM;
285
    std::unique_ptr<::comphelper::SequenceAsHashMap> m_pModulePropsHM;
286
287
    uno::Reference<beans::XPropertyAccess> m_xFilterProperties;
288
    uno::Reference<ui::dialogs::XAsynchronousExecutableDialog> m_xFilterDialog;
289
290
    ::comphelper::SequenceAsHashMap m_aMediaDescrHM;
291
292
    bool m_bRecommendReadOnly;
293
    bool m_bSignWithDefaultSignature;
294
295
    DECL_LINK(OptionsDialogClosedHdl, css::ui::dialogs::DialogClosedEvent*, void);
296
297
public:
298
    ModelData_Impl( SfxStoringHelper& aOwner,
299
                    uno::Reference< frame::XModel2 > xModel,
300
                    const uno::Sequence< beans::PropertyValue >& aMediaDescr );
301
302
    ~ModelData_Impl();
303
304
    void FreeDocumentProps();
305
306
    uno::Reference< frame::XModel2 > const & GetModel() const;
307
    uno::Reference< frame::XStorable > const & GetStorable();
308
    uno::Reference< frame::XStorable2 > const & GetStorable2();
309
310
0
    ::comphelper::SequenceAsHashMap& GetMediaDescr() { return m_aMediaDescrHM; }
311
312
0
    bool IsRecommendReadOnly() const { return m_bRecommendReadOnly; }
313
0
    bool IsSignWithDefaultSignature() const { return m_bSignWithDefaultSignature; }
314
315
    const ::comphelper::SequenceAsHashMap& GetDocProps();
316
317
    OUString const & GetModuleName();
318
    const ::comphelper::SequenceAsHashMap& GetModuleProps();
319
320
    void CheckInteractionHandler();
321
322
323
    OUString GetDocServiceName();
324
    uno::Sequence< beans::PropertyValue > GetDocServiceDefaultFilterCheckFlags( SfxFilterFlags nMust, SfxFilterFlags nDont );
325
    uno::Sequence< beans::PropertyValue > GetDocServiceAnyFilter( SfxFilterFlags nMust, SfxFilterFlags nDont );
326
    uno::Sequence< beans::PropertyValue > GetPreselectedFilter_Impl( sal_Int16 nStoreMode );
327
    uno::Sequence< beans::PropertyValue > GetDocServiceDefaultFilter();
328
329
    bool ExecuteFilterDialog_Impl( const OUString& aFilterName, bool bAsync );
330
331
    sal_Int8 CheckSaveAcceptable( sal_Int8 nCurStatus );
332
    sal_Int8 CheckStateForSave();
333
334
    sal_Int8 CheckFilter( const OUString& );
335
336
    bool CheckFilterOptionsDialogExistence();
337
338
    bool OutputFileDialog( sal_Int16 nStoreMode,
339
                                const ::comphelper::SequenceAsHashMap& aPreselectedFilterPropsHM,
340
                                bool bSetStandardName,
341
                                OUString& aSuggestedName,
342
                                bool bPreselectPassword,
343
                                OUString& aSuggestedDir,
344
                                sal_Int16 nDialog,
345
                                const css::uno::Sequence<OUString>& rDenyList,
346
                                SignatureState const nScriptingSignatureState
347
                                );
348
349
    bool ShowDocumentInfoDialog();
350
351
    static OUString GetRecommendedExtension( const OUString& aTypeName );
352
    OUString GetRecommendedName( const OUString& aSuggestedName,
353
                                        const OUString& aTypeName );
354
};
355
356
357
ModelData_Impl::ModelData_Impl( SfxStoringHelper& aOwner,
358
                                uno::Reference< frame::XModel2 > xModel,
359
                                const uno::Sequence< beans::PropertyValue >& aMediaDescr )
360
0
: m_pOwner( &aOwner )
361
0
, m_xModel(std::move( xModel ))
362
0
, m_aMediaDescrHM( aMediaDescr )
363
0
, m_bRecommendReadOnly( false )
364
0
, m_bSignWithDefaultSignature( false )
365
0
{
366
0
    CheckInteractionHandler();
367
0
}
368
369
370
ModelData_Impl::~ModelData_Impl()
371
0
{
372
0
    FreeDocumentProps();
373
0
    m_pDocumentPropsHM.reset();
374
0
    m_pModulePropsHM.reset();
375
0
    if (m_xFilterProperties)
376
0
        m_xFilterProperties.clear();
377
0
}
378
379
380
void ModelData_Impl::FreeDocumentProps()
381
0
{
382
0
    m_pDocumentPropsHM.reset();
383
0
}
384
385
386
uno::Reference< frame::XModel2 > const & ModelData_Impl::GetModel() const
387
0
{
388
0
    if ( !m_xModel.is() )
389
0
        throw uno::RuntimeException();
390
391
0
    return m_xModel;
392
0
}
393
394
uno::Reference< frame::XStorable > const & ModelData_Impl::GetStorable()
395
0
{
396
0
    if ( !m_xStorable.is() )
397
0
    {
398
0
        m_xStorable.set( m_xModel, uno::UNO_QUERY_THROW );
399
0
    }
400
401
0
    return m_xStorable;
402
0
}
403
404
405
uno::Reference< frame::XStorable2 > const & ModelData_Impl::GetStorable2()
406
0
{
407
0
    if ( !m_xStorable2.is() )
408
0
    {
409
0
        m_xStorable2.set( m_xModel, uno::UNO_QUERY_THROW );
410
0
    }
411
412
0
    return m_xStorable2;
413
0
}
414
415
416
const ::comphelper::SequenceAsHashMap& ModelData_Impl::GetDocProps()
417
0
{
418
0
    if ( !m_pDocumentPropsHM )
419
0
        m_pDocumentPropsHM.reset( new ::comphelper::SequenceAsHashMap( GetModel()->getArgs() ) );
420
421
0
    return *m_pDocumentPropsHM;
422
0
}
423
424
425
OUString const & ModelData_Impl::GetModuleName()
426
0
{
427
0
    if ( m_aModuleName.isEmpty() )
428
0
    {
429
0
        m_aModuleName = m_pOwner->GetModuleManager()->identify(
430
0
                                                uno::Reference< uno::XInterface >( m_xModel, uno::UNO_QUERY ) );
431
0
        if ( m_aModuleName.isEmpty() )
432
0
            throw uno::RuntimeException(); // TODO:
433
0
    }
434
0
    return m_aModuleName;
435
0
}
436
437
438
const ::comphelper::SequenceAsHashMap& ModelData_Impl::GetModuleProps()
439
0
{
440
0
    if ( !m_pModulePropsHM )
441
0
    {
442
0
        uno::Sequence< beans::PropertyValue > aModuleProps;
443
0
        m_pOwner->GetModuleManager()->getByName( GetModuleName() ) >>= aModuleProps;
444
0
        if ( !aModuleProps.hasElements() )
445
0
            throw uno::RuntimeException(); // TODO;
446
0
        m_pModulePropsHM.reset( new ::comphelper::SequenceAsHashMap( aModuleProps ) );
447
0
    }
448
449
0
    return *m_pModulePropsHM;
450
0
}
451
452
453
OUString ModelData_Impl::GetDocServiceName()
454
0
{
455
0
    return GetModuleProps().getUnpackedValueOrDefault(u"ooSetupFactoryDocumentService"_ustr, OUString());
456
0
}
457
458
459
void ModelData_Impl::CheckInteractionHandler()
460
0
{
461
0
    static constexpr OUString sInteractionHandler {u"InteractionHandler"_ustr};
462
0
    ::comphelper::SequenceAsHashMap::const_iterator aInteractIter =
463
0
            m_aMediaDescrHM.find( sInteractionHandler );
464
465
0
    if ( aInteractIter == m_aMediaDescrHM.end() )
466
0
    {
467
0
        try {
468
0
            m_aMediaDescrHM[ sInteractionHandler ]
469
0
                <<= task::InteractionHandler::createWithParent( comphelper::getProcessComponentContext(), nullptr);
470
0
        }
471
0
        catch( const uno::Exception& )
472
0
        {
473
0
        }
474
0
    }
475
0
    else
476
0
    {
477
0
        uno::Reference< task::XInteractionHandler > xInteract;
478
0
        DBG_ASSERT( ( aInteractIter->second >>= xInteract ) && xInteract.is(), "Broken interaction handler is provided!\n" );
479
0
    }
480
0
}
481
482
483
uno::Sequence< beans::PropertyValue > ModelData_Impl::GetDocServiceDefaultFilter()
484
0
{
485
0
    uno::Sequence< beans::PropertyValue > aProps;
486
487
0
    const OUString aFilterName = GetModuleProps().getUnpackedValueOrDefault( u"ooSetupFactoryDefaultFilter"_ustr, OUString() );
488
489
0
    m_pOwner->GetFilterConfiguration()->getByName( aFilterName ) >>= aProps;
490
491
0
    return aProps;
492
0
}
493
494
495
uno::Sequence< beans::PropertyValue > ModelData_Impl::GetDocServiceDefaultFilterCheckFlags( SfxFilterFlags nMust,
496
                                                                                            SfxFilterFlags nDont )
497
0
{
498
0
    uno::Sequence< beans::PropertyValue > aFilterProps;
499
0
    uno::Sequence< beans::PropertyValue > aProps = GetDocServiceDefaultFilter();
500
0
    if ( aProps.hasElements() )
501
0
    {
502
0
        ::comphelper::SequenceAsHashMap aFiltHM( aProps );
503
0
        SfxFilterFlags nFlags = static_cast<SfxFilterFlags>(aFiltHM.getUnpackedValueOrDefault(u"Flags"_ustr,
504
0
                                                        sal_Int32(0) ));
505
0
        if ( ( ( nFlags & nMust ) == nMust ) && !( nFlags & nDont ) )
506
0
            aFilterProps = std::move(aProps);
507
0
    }
508
509
0
    return aFilterProps;
510
0
}
511
512
513
uno::Sequence< beans::PropertyValue > ModelData_Impl::GetDocServiceAnyFilter( SfxFilterFlags nMust, SfxFilterFlags nDont )
514
0
{
515
0
    uno::Sequence< beans::NamedValue > aSearchRequest { { u"DocumentService"_ustr, css::uno::Any(GetDocServiceName()) } };
516
517
0
    return ::comphelper::MimeConfigurationHelper::SearchForFilter( m_pOwner->GetFilterQuery(), aSearchRequest, nMust, nDont );
518
0
}
519
520
521
uno::Sequence< beans::PropertyValue > ModelData_Impl::GetPreselectedFilter_Impl( sal_Int16 nStoreMode )
522
0
{
523
0
    if ( nStoreMode == SAVEASREMOTE_REQUESTED )
524
0
        nStoreMode = SAVEAS_REQUESTED;
525
526
0
    uno::Sequence< beans::PropertyValue > aFilterProps;
527
528
0
    SfxFilterFlags nMust = getMustFlags( nStoreMode );
529
0
    SfxFilterFlags nDont = getDontFlags( nStoreMode );
530
531
0
    if ( ( nStoreMode != SAVEASREMOTE_REQUESTED ) && ( nStoreMode & PDFEXPORT_REQUESTED ) )
532
0
    {
533
        // Preselect PDF-Filter for EXPORT
534
0
        uno::Sequence< beans::NamedValue > aSearchRequest
535
0
        {
536
0
            { u"Type"_ustr, css::uno::Any(u"pdf_Portable_Document_Format"_ustr) },
537
0
            { u"DocumentService"_ustr, css::uno::Any(GetDocServiceName()) }
538
0
        };
539
540
0
        aFilterProps = ::comphelper::MimeConfigurationHelper::SearchForFilter( m_pOwner->GetFilterQuery(), aSearchRequest, nMust, nDont );
541
0
    }
542
0
    else if ( ( nStoreMode != SAVEASREMOTE_REQUESTED ) && ( nStoreMode & EPUBEXPORT_REQUESTED ) )
543
0
    {
544
        // Preselect EPUB filter for export.
545
0
        uno::Sequence<beans::NamedValue> aSearchRequest
546
0
        {
547
0
            { u"Type"_ustr, css::uno::Any(u"writer_EPUB_Document"_ustr) },
548
0
            { u"DocumentService"_ustr, css::uno::Any(GetDocServiceName()) }
549
0
        };
550
551
0
        aFilterProps = ::comphelper::MimeConfigurationHelper::SearchForFilter( m_pOwner->GetFilterQuery(), aSearchRequest, nMust, nDont );
552
0
    }
553
0
    else
554
0
    {
555
0
        aFilterProps = GetDocServiceDefaultFilterCheckFlags( nMust, nDont );
556
557
0
        if ( !aFilterProps.hasElements() )
558
0
        {
559
            // the default filter was not found, use just the first acceptable one
560
0
            aFilterProps = GetDocServiceAnyFilter( nMust, nDont );
561
0
        }
562
0
    }
563
564
0
    return aFilterProps;
565
0
}
566
567
568
bool ModelData_Impl::ExecuteFilterDialog_Impl( const OUString& aFilterName, bool bIsAsync )
569
0
{
570
0
    bool bDialogUsed = false;
571
572
0
    try {
573
0
        uno::Sequence < beans::PropertyValue > aProps;
574
0
        uno::Any aAny = m_pOwner->GetFilterConfiguration()->getByName( aFilterName );
575
0
        if ( aAny >>= aProps )
576
0
        {
577
0
            auto pProp = std::find_if(std::cbegin(aProps), std::cend(aProps),
578
0
                [](const beans::PropertyValue& rProp) { return rProp.Name == "UIComponent"; });
579
0
            if (pProp != std::cend(aProps))
580
0
            {
581
0
                OUString aServiceName;
582
0
                pProp->Value >>= aServiceName;
583
0
                if( !aServiceName.isEmpty() )
584
0
                {
585
0
                    uno::Sequence<uno::Any> aDialogArgs(comphelper::InitAnyPropertySequence(
586
0
                    {
587
0
                        {"ParentWindow", uno::Any(SfxStoringHelper::GetModelXWindow(m_xModel))},
588
0
                    }));
589
590
0
                    uno::Reference< beans::XPropertyAccess > xFilterProperties;
591
0
                    uno::Reference< ui::dialogs::XExecutableDialog > xFilterDialog;
592
0
                    uno::Reference< ui::dialogs::XAsynchronousExecutableDialog > xAsyncFilterDialog;
593
0
                    uno::Reference< document::XExporter > xExporter;
594
595
0
                    if ( bIsAsync )
596
0
                    {
597
0
                        xAsyncFilterDialog = uno::Reference< ui::dialogs::XAsynchronousExecutableDialog >(
598
0
                            comphelper::getProcessServiceFactory()->createInstanceWithArguments( aServiceName, aDialogArgs ), uno::UNO_QUERY );
599
0
                        OSL_ENSURE(xAsyncFilterDialog.is(), "ModelData_Impl::ExecuteFilterDialog_Impl: Dialog is not async!");
600
0
                        xFilterProperties = uno::Reference< beans::XPropertyAccess >( xAsyncFilterDialog, uno::UNO_QUERY );
601
0
                        xExporter = uno::Reference< document::XExporter >( xAsyncFilterDialog, uno::UNO_QUERY );
602
0
                    }
603
0
                    else
604
0
                    {
605
0
                        xFilterDialog = uno::Reference< ui::dialogs::XExecutableDialog >(
606
0
                            comphelper::getProcessServiceFactory()->createInstanceWithArguments( aServiceName, aDialogArgs ), uno::UNO_QUERY );
607
0
                        xFilterProperties = uno::Reference< beans::XPropertyAccess >( xFilterDialog, uno::UNO_QUERY );
608
0
                        xExporter = uno::Reference< document::XExporter >( xFilterDialog, uno::UNO_QUERY );
609
0
                    }
610
611
0
                    if ( xFilterProperties.is() && ( xFilterDialog.is() || xAsyncFilterDialog.is() ) )
612
0
                    {
613
0
                        bDialogUsed = true;
614
615
0
                        if( xExporter.is() )
616
0
                            xExporter->setSourceDocument( GetModel() );
617
618
0
                        uno::Sequence< beans::PropertyValue > aPropsForDialog;
619
0
                        GetMediaDescr() >> aPropsForDialog;
620
0
                        xFilterProperties->setPropertyValues( aPropsForDialog );
621
622
0
                        if ( bIsAsync )
623
0
                        {
624
0
                            m_xFilterProperties = std::move(xFilterProperties);
625
0
                            m_xFilterDialog = std::move(xAsyncFilterDialog);
626
627
0
                            auto aDialogClosedListener = rtl::Reference(new svt::DialogClosedListener());
628
0
                            aDialogClosedListener->SetDialogClosedLink( LINK( this, ModelData_Impl, OptionsDialogClosedHdl ) );
629
630
0
                            m_xFilterDialog->startExecuteModal( aDialogClosedListener );
631
0
                        }
632
0
                        else
633
0
                        {
634
0
                            if( !xFilterDialog->execute() )
635
0
                            {
636
0
                                throw task::ErrorCodeIOException(
637
0
                                    (u"ModelData_Impl::ExecuteFilterDialog_Impl:"
638
0
                                    " ERRCODE_IO_ABORT"_ustr),
639
0
                                    uno::Reference< uno::XInterface >(),
640
0
                                    sal_uInt32(ERRCODE_IO_ABORT));
641
0
                            }
642
643
0
                            const uno::Sequence< beans::PropertyValue > aPropsFromDialog =
644
0
                                                                        xFilterProperties->getPropertyValues();
645
0
                            for ( const auto& rProp : aPropsFromDialog )
646
0
                                GetMediaDescr()[rProp.Name] = rProp.Value;
647
0
                        }
648
0
                    }
649
0
                }
650
0
            }
651
0
        }
652
0
    }
653
0
    catch( const container::NoSuchElementException& e )
654
0
    {
655
        // the filter name is unknown
656
0
        throw task::ErrorCodeIOException(
657
0
            ("ModelData_Impl::ExecuteFilterDialog_Impl: NoSuchElementException"
658
0
             " \"" + e.Message + "\": ERRCODE_IO_ABORT"),
659
0
            uno::Reference< uno::XInterface >(), sal_uInt32(ERRCODE_IO_INVALIDPARAMETER));
660
0
    }
661
0
    catch( const task::ErrorCodeIOException& )
662
0
    {
663
0
        throw;
664
0
    }
665
0
    catch( const uno::Exception& )
666
0
    {
667
0
        TOOLS_WARN_EXCEPTION("sfx.doc", "ignoring");
668
0
    }
669
670
0
    return bDialogUsed;
671
0
}
672
673
void SfxStoringHelper::CallFinishGUIStoreModel()
674
0
{
675
0
    ::comphelper::SequenceAsHashMap::const_iterator aFileNameIter = m_xModelData->GetMediaDescr().find( u"URL"_ustr );
676
0
    uno::Sequence< beans::PropertyValue > aFilterProps = m_xModelData->GetPreselectedFilter_Impl( m_nStoreMode );
677
0
    const OUString aFilterFromMediaDescr = m_xModelData->GetMediaDescr().getUnpackedValueOrDefault( aFilterNameString, OUString() );
678
0
    const OUString aOldFilterName = m_xModelData->GetDocProps().getUnpackedValueOrDefault( aFilterNameString, OUString() );
679
0
    ::comphelper::SequenceAsHashMap aFilterPropsHM( aFilterProps );
680
0
    OUString aFilterName = aFilterPropsHM.getUnpackedValueOrDefault( u"Name"_ustr, OUString() );
681
682
0
    SfxStoringHelper::FinishGUIStoreModel(aFileNameIter, *m_xModelData, m_bRemote, m_nStoreMode, aFilterProps,
683
0
                                          m_bSetStandardName, m_bPreselectPassword, m_bDialogUsed,
684
0
                                          aFilterFromMediaDescr, aOldFilterName, m_aArgsSequence,
685
0
                                          aFilterName, m_nScriptingSignatureState);
686
687
0
    if (SfxViewShell::Current())
688
0
        SfxViewShell::Current()->SetStoringHelper(nullptr);
689
0
}
690
691
IMPL_LINK( ModelData_Impl, OptionsDialogClosedHdl, css::ui::dialogs::DialogClosedEvent*, pEvt, void )
692
0
{
693
0
    SfxViewShell* pNotifier = comphelper::LibreOfficeKit::isActive() ? SfxViewShell::Current() : nullptr;
694
695
0
    if (pEvt->DialogResult == RET_OK && m_xFilterProperties)
696
0
    {
697
0
        if (pNotifier)
698
0
            pNotifier->libreOfficeKitViewCallback( LOK_CALLBACK_EXPORT_FILE, "PENDING"_ostr );
699
700
0
        const uno::Sequence< beans::PropertyValue > aPropsFromDialog = m_xFilterProperties->getPropertyValues();
701
0
        for ( const auto& rProp : aPropsFromDialog )
702
0
            GetMediaDescr()[rProp.Name] = rProp.Value;
703
704
0
        m_pOwner->CallFinishGUIStoreModel();
705
0
    }
706
0
    else if (pNotifier)
707
0
    {
708
0
        pNotifier->libreOfficeKitViewCallback( LOK_CALLBACK_EXPORT_FILE, "ABORT"_ostr );
709
0
    }
710
0
}
711
712
sal_Int8 ModelData_Impl::CheckSaveAcceptable( sal_Int8 nCurStatus )
713
0
{
714
0
    sal_Int8 nResult = nCurStatus;
715
716
0
    if ( nResult != STATUS_NO_ACTION && GetStorable()->hasLocation() )
717
0
    {
718
        // the saving is acceptable
719
        // in case the configuration entry is not set or set to false
720
        // or in case of version creation
721
0
        if ( officecfg::Office::Common::Save::Document::AlwaysSaveAs::get()
722
0
          && GetMediaDescr().find( u"VersionComment"_ustr ) == GetMediaDescr().end() )
723
0
        {
724
            // notify the user that SaveAs is going to be done
725
0
            std::unique_ptr<weld::MessageDialog> xMessageBox(Application::CreateMessageDialog(SfxStoringHelper::GetModelWindow(m_xModel),
726
0
                                                             VclMessageType::Question, VclButtonsType::OkCancel, SfxResId(STR_NEW_FILENAME_SAVE)));
727
0
            if (xMessageBox->run() == RET_OK)
728
0
                nResult = STATUS_SAVEAS;
729
0
            else
730
0
                nResult = STATUS_NO_ACTION;
731
0
        }
732
0
    }
733
734
0
    return nResult;
735
0
}
736
737
738
sal_Int8 ModelData_Impl::CheckStateForSave()
739
0
{
740
    // if the document is readonly or a new one a SaveAs operation must be used
741
0
    if ( !GetStorable()->hasLocation() || GetStorable()->isReadonly() )
742
0
        return STATUS_SAVEAS;
743
744
    // check acceptable entries for media descriptor
745
0
    ::comphelper::SequenceAsHashMap aAcceptedArgs;
746
747
0
    static constexpr OUString aVersionCommentString(u"VersionComment"_ustr);
748
0
    static constexpr OUString aAuthorString(u"Author"_ustr);
749
0
    static constexpr OUString aDontTerminateEdit(u"DontTerminateEdit"_ustr);
750
0
    static constexpr OUString aInteractionHandlerString(u"InteractionHandler"_ustr);
751
0
    static constexpr OUString aStatusIndicatorString(u"StatusIndicator"_ustr);
752
0
    static constexpr OUString aFailOnWarningString(u"FailOnWarning"_ustr);
753
0
    static constexpr OUString aNoFileSync(u"NoFileSync"_ustr);
754
755
0
    if ( GetMediaDescr().find( aVersionCommentString ) != GetMediaDescr().end() )
756
0
        aAcceptedArgs[ aVersionCommentString ] = GetMediaDescr()[ aVersionCommentString ];
757
0
    if ( GetMediaDescr().find( aAuthorString ) != GetMediaDescr().end() )
758
0
        aAcceptedArgs[ aAuthorString ] = GetMediaDescr()[ aAuthorString ];
759
0
    if ( GetMediaDescr().find( aDontTerminateEdit ) != GetMediaDescr().end() )
760
0
        aAcceptedArgs[ aDontTerminateEdit ] = GetMediaDescr()[ aDontTerminateEdit ];
761
0
    if ( GetMediaDescr().find( aInteractionHandlerString ) != GetMediaDescr().end() )
762
0
        aAcceptedArgs[ aInteractionHandlerString ] = GetMediaDescr()[ aInteractionHandlerString ];
763
0
    if ( GetMediaDescr().find( aStatusIndicatorString ) != GetMediaDescr().end() )
764
0
        aAcceptedArgs[ aStatusIndicatorString ] = GetMediaDescr()[ aStatusIndicatorString ];
765
0
    if ( GetMediaDescr().find( aFailOnWarningString ) != GetMediaDescr().end() )
766
0
        aAcceptedArgs[ aFailOnWarningString ] = GetMediaDescr()[ aFailOnWarningString ];
767
0
    if (GetMediaDescr().find(aNoFileSync) != GetMediaDescr().end())
768
0
        aAcceptedArgs[aNoFileSync] = GetMediaDescr()[aNoFileSync];
769
770
    // remove unacceptable entry if there is any
771
0
    DBG_ASSERT( GetMediaDescr().size() == aAcceptedArgs.size(),
772
0
                "Unacceptable parameters are provided in Save request!\n" );
773
0
    if ( GetMediaDescr().size() != aAcceptedArgs.size() )
774
0
        GetMediaDescr() = std::move(aAcceptedArgs);
775
776
    // check that the old filter is acceptable
777
0
    return CheckFilter( GetDocProps().getUnpackedValueOrDefault(aFilterNameString, OUString()) );
778
0
}
779
780
sal_Int8 ModelData_Impl::CheckFilter( const OUString& aFilterName )
781
0
{
782
0
    ::comphelper::SequenceAsHashMap aFiltPropsHM;
783
0
    SfxFilterFlags nFiltFlags = SfxFilterFlags::NONE;
784
0
    if ( !aFilterName.isEmpty() )
785
0
    {
786
        // get properties of filter
787
0
        uno::Sequence< beans::PropertyValue > aFilterProps;
788
0
        m_pOwner->GetFilterConfiguration()->getByName( aFilterName ) >>= aFilterProps;
789
790
0
        aFiltPropsHM = ::comphelper::SequenceAsHashMap( aFilterProps );
791
0
        nFiltFlags = static_cast<SfxFilterFlags>(aFiltPropsHM.getUnpackedValueOrDefault(u"Flags"_ustr, sal_Int32(0) ));
792
0
    }
793
794
    // only a temporary solution until default filter retrieving feature is implemented
795
    // then GetDocServiceDefaultFilter() must be used
796
0
    ::comphelper::SequenceAsHashMap aDefFiltPropsHM = GetDocServiceDefaultFilterCheckFlags( SfxFilterFlags::IMPORT | SfxFilterFlags::EXPORT, SfxFilterFlags::NONE );
797
0
    SfxFilterFlags nDefFiltFlags = static_cast<SfxFilterFlags>(aDefFiltPropsHM.getUnpackedValueOrDefault(u"Flags"_ustr, sal_Int32(0) ));
798
799
0
    bool bAsk = false;
800
801
    // if the old filter is not acceptable
802
    // and there is no default filter or it is not acceptable for requested parameters then proceed with saveAs
803
0
    if ( ( aFiltPropsHM.empty() || !( nFiltFlags & SfxFilterFlags::EXPORT ) )
804
0
      && ( aDefFiltPropsHM.empty() || !( nDefFiltFlags & SfxFilterFlags::EXPORT ) || nDefFiltFlags & SfxFilterFlags::INTERNAL ) )
805
0
        return STATUS_SAVEAS;
806
807
    // so at this point there is either an acceptable old filter or default one
808
0
    if ( aFiltPropsHM.empty() || !( nFiltFlags & SfxFilterFlags::EXPORT ) )
809
0
    {
810
        // so the default filter must be acceptable
811
0
        return STATUS_SAVEAS_STANDARDNAME;
812
0
    }
813
0
    else if ( ( !( nFiltFlags & SfxFilterFlags::OWN ) || ( nFiltFlags & SfxFilterFlags::ALIEN ) )
814
0
           && !aDefFiltPropsHM.empty()
815
0
           && ( nDefFiltFlags & SfxFilterFlags::EXPORT ) && !( nDefFiltFlags & SfxFilterFlags::INTERNAL ))
816
0
    {
817
0
        bAsk = true;
818
0
    }
819
820
    // check if EncryptionData supports this output format
821
0
    {
822
0
        OUString aSupportedFilters;
823
0
        const ::comphelper::SequenceAsHashMap& rDocumentProperties = GetDocProps();
824
0
        const css::uno::Sequence<css::beans::NamedValue> aEncryptionData = rDocumentProperties.getUnpackedValueOrDefault(u"EncryptionData"_ustr, css::uno::Sequence<css::beans::NamedValue>());
825
0
        if (aEncryptionData != css::uno::Sequence<css::beans::NamedValue>())
826
0
        {
827
0
            for (const css::beans::NamedValue& aNamedValue : aEncryptionData)
828
0
            {
829
0
                if (aNamedValue.Name == "SupportedFilters")
830
0
                {
831
0
                    aNamedValue.Value >>= aSupportedFilters;
832
0
                }
833
0
            }
834
0
        }
835
836
        // if 'SupportedFilters' is empty assume that all filters are supported.
837
0
        if (!aSupportedFilters.isEmpty())
838
0
        {
839
0
            const OUString aSelectedFilter = aFiltPropsHM.getUnpackedValueOrDefault(u"UIName"_ustr, OUString());
840
841
0
            aSupportedFilters = ";" + aSupportedFilters + ";";
842
0
            const OUString aSearchToken = ";" + aSelectedFilter + ";";
843
0
            bAsk = (aSupportedFilters.indexOf(aSearchToken) < 0);
844
0
        }
845
0
    }
846
847
0
    if (bAsk)
848
0
    {
849
        // the default filter is acceptable and the old filter is alien one
850
        // so ask to make a saveAs operation
851
0
        const OUString aUIName = aFiltPropsHM.getUnpackedValueOrDefault(u"UIName"_ustr, OUString() );
852
0
        const OUString aType = aFiltPropsHM.getUnpackedValueOrDefault( u"Type"_ustr, OUString() );
853
0
        const OUString aExtension = GetRecommendedExtension(aType);
854
0
        const OUString aPreusedFilterName = GetDocProps().getUnpackedValueOrDefault(u"PreusedFilterName"_ustr, OUString() );
855
0
        const OUString aDefUIName = aDefFiltPropsHM.getUnpackedValueOrDefault(u"UIName"_ustr, OUString() );
856
0
        const OUString aDefType = aDefFiltPropsHM.getUnpackedValueOrDefault( u"Type"_ustr, OUString() );
857
0
        const OUString aDefExtension = GetRecommendedExtension( aDefType );
858
859
0
        if ( aPreusedFilterName != aFilterName && aUIName != aDefUIName )
860
0
        {
861
0
            if ( !SfxStoringHelper::WarnUnacceptableFormat( GetModel(), aUIName,aExtension, aDefExtension,
862
0
                                                            static_cast<bool>( nDefFiltFlags & SfxFilterFlags::ALIEN ) ) )
863
0
                return STATUS_SAVEAS_STANDARDNAME;
864
0
        }
865
0
    }
866
867
0
    return STATUS_SAVE;
868
0
}
869
870
871
bool ModelData_Impl::CheckFilterOptionsDialogExistence()
872
0
{
873
0
    uno::Sequence< beans::NamedValue > aSearchRequest { { u"DocumentService"_ustr, css::uno::Any(GetDocServiceName()) } };
874
875
0
    uno::Reference< container::XEnumeration > xFilterEnum =
876
0
                                    m_pOwner->GetFilterQuery()->createSubSetEnumerationByProperties( aSearchRequest );
877
878
0
    while ( xFilterEnum->hasMoreElements() )
879
0
    {
880
0
        uno::Sequence< beans::PropertyValue > aProps;
881
0
        if ( xFilterEnum->nextElement() >>= aProps )
882
0
        {
883
0
            ::comphelper::SequenceAsHashMap aPropsHM( aProps );
884
0
            if ( !aPropsHM.getUnpackedValueOrDefault(u"UIComponent"_ustr, OUString()).isEmpty() )
885
0
                return true;
886
0
        }
887
0
    }
888
889
0
    return false;
890
0
}
891
892
893
bool ModelData_Impl::OutputFileDialog( sal_Int16 nStoreMode,
894
                                            const ::comphelper::SequenceAsHashMap& aPreselectedFilterPropsHM,
895
                                            bool bSetStandardName,
896
                                            OUString& aSuggestedName,
897
                                            bool bPreselectPassword,
898
                                            OUString& aSuggestedDir,
899
                                            sal_Int16 nDialog,
900
                                            const css::uno::Sequence<OUString>& rDenyList,
901
                                            SignatureState const nScriptingSignatureState)
902
0
{
903
0
    if ( nStoreMode == SAVEASREMOTE_REQUESTED )
904
0
        nStoreMode = SAVEAS_REQUESTED;
905
906
0
    bool bUseFilterOptions = false;
907
908
0
    ::comphelper::SequenceAsHashMap::const_iterator aOverwriteIter =
909
0
                GetMediaDescr().find( u"Overwrite"_ustr );
910
911
    // the file name must be specified if overwrite option is set
912
0
    if ( aOverwriteIter != GetMediaDescr().end() )
913
0
           throw task::ErrorCodeIOException(
914
0
               u"ModelData_Impl::OutputFileDialog: ERRCODE_IO_INVALIDPARAMETER"_ustr,
915
0
               uno::Reference< uno::XInterface >(),
916
0
               sal_uInt32(ERRCODE_IO_INVALIDPARAMETER));
917
918
    // no target file name is specified
919
    // we need to show the file dialog
920
921
    // check if we have a filter which allows for filter options, so we need a corresponding checkbox in the dialog
922
0
    bool bAllowOptions = false;
923
924
    // in case of Export, filter options dialog is used if available
925
0
    if( !( nStoreMode & EXPORT_REQUESTED ) || ( nStoreMode & WIDEEXPORT_REQUESTED ) )
926
0
        bAllowOptions = CheckFilterOptionsDialogExistence();
927
928
    // get the filename by dialog ...
929
    // create the file dialog
930
0
    sal_Int16  aDialogMode = bAllowOptions
931
0
        ? css::ui::dialogs::TemplateDescription::FILESAVE_AUTOEXTENSION_PASSWORD_FILTEROPTIONS
932
0
        : css::ui::dialogs::TemplateDescription::FILESAVE_AUTOEXTENSION_PASSWORD;
933
0
    FileDialogFlags aDialogFlags = FileDialogFlags::NONE;
934
935
0
    if( ( nStoreMode & EXPORT_REQUESTED ) && !( nStoreMode & WIDEEXPORT_REQUESTED ) )
936
0
    {
937
0
        if ( (nStoreMode & PDFEXPORT_REQUESTED) || (nStoreMode & EPUBEXPORT_REQUESTED) )
938
0
            aDialogMode = css::ui::dialogs::TemplateDescription::
939
0
                FILESAVE_AUTOEXTENSION;
940
0
        else
941
0
            aDialogMode = css::ui::dialogs::TemplateDescription::
942
0
                FILESAVE_AUTOEXTENSION_SELECTION;
943
0
        aDialogFlags = FileDialogFlags::Export;
944
0
    }
945
946
0
    if( ( nStoreMode & EXPORT_REQUESTED ) && ( nStoreMode & SAVEACOPY_REQUESTED ) && ( nStoreMode & WIDEEXPORT_REQUESTED ) )
947
0
    {
948
0
        aDialogFlags = FileDialogFlags::SaveACopy;
949
0
    }
950
951
0
    std::unique_ptr<sfx2::FileDialogHelper> pFileDlg;
952
953
0
    const OUString aDocServiceName {GetDocServiceName()};
954
0
    DBG_ASSERT( !aDocServiceName.isEmpty(), "No document service for this module set!" );
955
956
0
    SfxFilterFlags nMust = getMustFlags( nStoreMode );
957
0
    SfxFilterFlags nDont = getDontFlags( nStoreMode );
958
0
    weld::Window* pFrameWin = SfxStoringHelper::GetModelWindow(m_xModel);
959
0
    OUString sPreselectedDir
960
0
        = GetDocProps().getUnpackedValueOrDefault("ExportDirectory", OUString());
961
962
    // Fall back to the document base URL - but only if the document is not based on a template.
963
    // Otherwise the template's directory would be used, which is not what we want.
964
0
    if (SfxViewShell* pViewShell = SfxViewShell::Current())
965
0
    {
966
0
        SfxObjectShell* pDocShell = pViewShell->GetObjectShell();
967
0
        if (pDocShell && !pDocShell->IsBasedOnTemplate())
968
0
        {
969
0
            if (sPreselectedDir.isEmpty())
970
0
                sPreselectedDir = GetDocProps().getUnpackedValueOrDefault("DocumentBaseURL", OUString());
971
0
            if (sPreselectedDir.isEmpty() && GetStorable()->hasLocation())
972
0
                sPreselectedDir = GetStorable()->getLocation();
973
0
        }
974
0
    }
975
976
0
    INetURLObject aObj(sPreselectedDir);
977
0
    aObj.removeSegment(); // remove file name from URL
978
0
    sPreselectedDir = aObj.GetMainURL(INetURLObject::DecodeMechanism::NONE);
979
0
    if ( ( nStoreMode & EXPORT_REQUESTED ) && !( nStoreMode & WIDEEXPORT_REQUESTED ) )
980
0
    {
981
0
        if ( ( nStoreMode & PDFEXPORT_REQUESTED ) && !aPreselectedFilterPropsHM.empty() )
982
0
        {
983
            // this is a PDF export
984
            // the filter options has been shown already
985
0
            const OUString aFilterUIName = aPreselectedFilterPropsHM.getUnpackedValueOrDefault( u"UIName"_ustr, OUString() );
986
0
            pFileDlg.reset(new sfx2::FileDialogHelper( aDialogMode, aDialogFlags, aFilterUIName, u"pdf", sPreselectedDir, rDenyList, pFrameWin ));
987
0
            pFileDlg->SetCurrentFilter( aFilterUIName );
988
0
        }
989
0
        else if ((nStoreMode & EPUBEXPORT_REQUESTED) && !aPreselectedFilterPropsHM.empty())
990
0
        {
991
            // This is an EPUB export, the filter options has been shown already.
992
0
            const OUString aFilterUIName = aPreselectedFilterPropsHM.getUnpackedValueOrDefault( u"UIName"_ustr, OUString() );
993
0
            pFileDlg.reset(new sfx2::FileDialogHelper(aDialogMode, aDialogFlags, aFilterUIName, u"epub", sPreselectedDir, rDenyList, pFrameWin));
994
0
            pFileDlg->SetCurrentFilter(aFilterUIName);
995
0
        }
996
0
        else
997
0
        {
998
            // This is the normal dialog
999
0
            pFileDlg.reset(new sfx2::FileDialogHelper( aDialogMode, aDialogFlags, aDocServiceName, nDialog, nMust, nDont, sPreselectedDir, rDenyList, pFrameWin ));
1000
0
        }
1001
1002
0
        sfx2::FileDialogHelper::Context eCtxt = sfx2::FileDialogHelper::UnknownContext;
1003
0
        if ( aDocServiceName == "com.sun.star.drawing.DrawingDocument" )
1004
0
            eCtxt = sfx2::FileDialogHelper::DrawExport;
1005
0
        else if ( aDocServiceName == "com.sun.star.presentation.PresentationDocument" )
1006
0
            eCtxt = sfx2::FileDialogHelper::ImpressExport;
1007
0
        else if ( aDocServiceName == "com.sun.star.text.TextDocument" )
1008
0
            eCtxt = sfx2::FileDialogHelper::WriterExport;
1009
0
        else if ( aDocServiceName == "com.sun.star.sheet.SpreadsheetDocument" )
1010
0
            eCtxt = sfx2::FileDialogHelper::CalcExport;
1011
0
        if ( eCtxt != sfx2::FileDialogHelper::UnknownContext )
1012
0
               pFileDlg->SetContext( eCtxt );
1013
1014
0
        pFileDlg->CreateMatcher( aDocServiceName );
1015
1016
0
        uno::Reference< ui::dialogs::XFilePicker3 > xFilePicker = pFileDlg->GetFilePicker();
1017
0
        uno::Reference< ui::dialogs::XFilePickerControlAccess > xControlAccess( xFilePicker, uno::UNO_QUERY );
1018
1019
0
        if ( xControlAccess.is() )
1020
0
        {
1021
0
            xControlAccess->setLabel( ui::dialogs::CommonFilePickerElementIds::PUSHBUTTON_OK, SfxResId(STR_EXPORTBUTTON) );
1022
0
            xControlAccess->setLabel( ui::dialogs::CommonFilePickerElementIds::LISTBOX_FILTER_LABEL, SfxResId(STR_LABEL_FILEFORMAT) );
1023
0
        }
1024
0
    }
1025
0
    else
1026
0
    {
1027
        // This is the normal save as dialog
1028
0
        pFileDlg.reset(new sfx2::FileDialogHelper( aDialogMode, aDialogFlags, aDocServiceName, nDialog,
1029
0
            nMust, nDont, sPreselectedDir, rDenyList, pFrameWin ));
1030
0
        pFileDlg->CreateMatcher( aDocServiceName );
1031
1032
0
        sfx2::FileDialogHelper::Context eCtxt = sfx2::FileDialogHelper::UnknownContext;
1033
0
        if ( aDocServiceName == "com.sun.star.drawing.DrawingDocument" )
1034
0
            eCtxt = sfx2::FileDialogHelper::DrawSaveAs;
1035
0
        else if ( aDocServiceName == "com.sun.star.presentation.PresentationDocument" )
1036
0
            eCtxt = sfx2::FileDialogHelper::ImpressSaveAs;
1037
0
        else if ( aDocServiceName == "com.sun.star.text.TextDocument" )
1038
0
            eCtxt = sfx2::FileDialogHelper::WriterSaveAs;
1039
0
        else if ( aDocServiceName == "com.sun.star.sheet.SpreadsheetDocument" )
1040
0
            eCtxt = sfx2::FileDialogHelper::CalcSaveAs;
1041
1042
0
        if ( eCtxt != sfx2::FileDialogHelper::UnknownContext )
1043
0
               pFileDlg->SetContext( eCtxt );
1044
0
    }
1045
1046
0
    OUString aAdjustToType;
1047
1048
0
    const OUString sFilterNameString(aFilterNameString);
1049
1050
0
    if ( ( nStoreMode & EXPORT_REQUESTED ) && !( nStoreMode & WIDEEXPORT_REQUESTED ) )
1051
0
    {
1052
        // it is export, set the preselected filter
1053
0
        pFileDlg->SetCurrentFilter( aPreselectedFilterPropsHM.getUnpackedValueOrDefault( u"UIName"_ustr, OUString() ) );
1054
0
        aAdjustToType = aPreselectedFilterPropsHM.getUnpackedValueOrDefault( u"Type"_ustr, OUString() );
1055
0
    }
1056
    // it is no export, bSetStandardName == true means that user agreed to store document in the default (default default ;-)) format
1057
0
    else if ( bSetStandardName || GetStorable()->hasLocation() )
1058
0
    {
1059
0
        uno::Sequence< beans::PropertyValue > aOldFilterProps;
1060
0
        const OUString aOldFilterName = GetDocProps().getUnpackedValueOrDefault( sFilterNameString, OUString() );
1061
1062
0
        if ( !aOldFilterName.isEmpty() )
1063
0
            m_pOwner->GetFilterConfiguration()->getByName( aOldFilterName ) >>= aOldFilterProps;
1064
1065
0
        ::comphelper::SequenceAsHashMap aOldFiltPropsHM( aOldFilterProps );
1066
0
        SfxFilterFlags nOldFiltFlags = static_cast<SfxFilterFlags>(aOldFiltPropsHM.getUnpackedValueOrDefault(u"Flags"_ustr, sal_Int32(0) ));
1067
1068
0
        if ( bSetStandardName || ( nOldFiltFlags & nMust ) != nMust || bool(nOldFiltFlags & nDont) )
1069
0
        {
1070
            // the suggested type will be changed, the extension should be adjusted
1071
0
            aAdjustToType = aPreselectedFilterPropsHM.getUnpackedValueOrDefault( u"Type"_ustr, OUString() );
1072
0
            pFileDlg->SetCurrentFilter( aPreselectedFilterPropsHM.getUnpackedValueOrDefault( u"UIName"_ustr, OUString() ) );
1073
0
        }
1074
0
        else
1075
0
        {
1076
0
            pFileDlg->SetCurrentFilter( aOldFiltPropsHM.getUnpackedValueOrDefault(
1077
0
                                                        u"UIName"_ustr,
1078
0
                                                        OUString() ) );
1079
0
        }
1080
0
    }
1081
1082
0
    if ( !aSuggestedDir.isEmpty() )
1083
0
        pFileDlg->SetDisplayFolder( aSuggestedDir );
1084
0
    const OUString aRecommendedName {GetRecommendedName( aSuggestedName, aAdjustToType )};
1085
0
    if ( !aRecommendedName.isEmpty() )
1086
0
        pFileDlg->SetFileName( aRecommendedName );
1087
1088
0
    uno::Reference < view::XSelectionSupplier > xSel( GetModel()->getCurrentController(), uno::UNO_QUERY );
1089
0
    if ( xSel.is() && xSel->getSelection().hasValue() )
1090
0
        GetMediaDescr()[u"SelectionOnly"_ustr] <<= true;
1091
1092
    // This is a temporary hardcoded solution must be removed when
1093
    // dialogs do not need parameters in SidSet representation any more
1094
0
    sal_uInt16 nSlotID = getSlotIDFromMode( nStoreMode );
1095
0
    if ( !nSlotID )
1096
0
        throw lang::IllegalArgumentException(); // TODO:
1097
1098
    // generate SidSet from MediaDescriptor and provide it into FileDialog
1099
    // than merge changed SidSet back
1100
0
    std::optional<SfxAllItemSet> pDialogParams( SfxGetpApp()->GetPool() );
1101
0
    TransformParameters( nSlotID,
1102
0
                         GetMediaDescr().getAsConstPropertyValueList(),
1103
0
                         *pDialogParams );
1104
1105
0
    if ( bPreselectPassword && !pDialogParams->HasItem( SID_ENCRYPTIONDATA ) )
1106
0
    {
1107
        // the file dialog preselects the password checkbox if the provided mediadescriptor has encryption data entry
1108
        // after dialog execution the password interaction flag will be either removed or not
1109
0
        pDialogParams->Put( SfxBoolItem( SID_PASSWORDINTERACTION, true ) );
1110
0
    }
1111
1112
    // aFilterName is a pure output parameter, pDialogParams is an in/out parameter
1113
0
    OUString aFilterName;
1114
    // in LOK case we don't show File Picker so it will fail, but execute to do other preparations
1115
0
    if (pFileDlg->Execute(pDialogParams, aFilterName, nScriptingSignatureState) != ERRCODE_NONE
1116
0
        && !comphelper::LibreOfficeKit::isActive() )
1117
0
    {
1118
0
        throw task::ErrorCodeIOException(
1119
0
            u"ModelData_Impl::OutputFileDialog: ERRCODE_IO_ABORT"_ustr,
1120
0
            uno::Reference< uno::XInterface >(), sal_uInt32(ERRCODE_IO_ABORT));
1121
0
    }
1122
0
    else if (comphelper::LibreOfficeKit::isActive())
1123
0
    {
1124
0
        aFilterName = aPreselectedFilterPropsHM.getUnpackedValueOrDefault( u"Name"_ustr, OUString() );
1125
0
    }
1126
1127
    // the following two arguments can not be converted in MediaDescriptor,
1128
    // so they should be removed from the ItemSet after retrieving
1129
0
    const SfxBoolItem* pRecommendReadOnly = pDialogParams->GetItem(SID_RECOMMENDREADONLY, false);
1130
0
    m_bRecommendReadOnly = ( pRecommendReadOnly && pRecommendReadOnly->GetValue() );
1131
0
    pDialogParams->ClearItem( SID_RECOMMENDREADONLY );
1132
1133
0
    const SfxBoolItem* pSignWithDefaultKey = pDialogParams->GetItem(SID_GPGSIGN, false);
1134
0
    m_bSignWithDefaultSignature = (pSignWithDefaultKey && pSignWithDefaultKey->GetValue());
1135
0
    pDialogParams->ClearItem( SID_GPGSIGN );
1136
1137
0
    GetMediaDescr() = TransformItems(nSlotID, *pDialogParams);
1138
1139
    // get the path from the dialog
1140
0
    INetURLObject aURL( pFileDlg->GetPath() );
1141
1142
0
    if (comphelper::LibreOfficeKit::isActive())
1143
0
    {
1144
#ifdef IOS
1145
        // The iOS app (and maybe the Android app) have fails to set the URL to
1146
        // save to so we need to set it to a temporary file.
1147
        // Note: the iOS app is responsible for deleting the temporary file.
1148
        if (nStoreMode & EXPORT_REQUESTED && aURL.GetMainURL(INetURLObject::DecodeMechanism::NONE).isEmpty())
1149
        {
1150
            // Mirror the "export/docbasename.pdf" path format to match the
1151
            // format used in the "downloadas" message handler in the iOS app's
1152
            // -[DocumentViewController userContentController:didReceiveScriptMessage]
1153
            // selector.
1154
            // Important note: temporary files created here must be in their
1155
            // own subdirectory since the iOS app's UIDocumentPickerDelegate
1156
            // will try to delete both the temporary file and its parent
1157
            // directory.
1158
            OUString aFullName = u"export/" + aRecommendedName;
1159
            OUString aBaseName;
1160
            OUString aExtension;
1161
            sal_Int32 nPos = aFullName.lastIndexOf( '.' );
1162
            if ( nPos >= 0 )
1163
            {
1164
                aBaseName = aFullName.copy(0, nPos);
1165
                aExtension = aFullName.copy(nPos, aFullName.getLength() - nPos);
1166
            }
1167
            aURL = INetURLObject(::utl::CreateTempURL( aBaseName, false, aExtension, nullptr, true));
1168
1169
            // Remove any stale files left from a previous export
1170
            OUString fileURL = aURL.GetMainURL(INetURLObject::DecodeMechanism::NONE);
1171
            if (!fileURL.isEmpty())
1172
                osl::File::remove(fileURL);
1173
        }
1174
        else
1175
        {
1176
#endif
1177
            // keep name with extension
1178
0
            aSuggestedName = aRecommendedName;
1179
0
            OUString aExtension;
1180
0
            if (size_t nPos = aSuggestedName.lastIndexOf('.') + 1)
1181
0
                aExtension = aSuggestedName.copy(nPos, aSuggestedName.getLength() - nPos);
1182
0
            aURL.SetExtension(aExtension);
1183
#ifdef IOS
1184
        }
1185
#endif
1186
0
    }
1187
0
    else
1188
0
    {
1189
        // the path should be provided outside since it might be used for further calls to the dialog
1190
0
        aSuggestedName = aURL.GetLastName(INetURLObject::DecodeMechanism::WithCharset);
1191
0
    }
1192
0
    aSuggestedDir = pFileDlg->GetDisplayDirectory();
1193
1194
    // old filter options should be cleared in case different filter is used
1195
1196
0
    const OUString aFilterFromMediaDescr = GetMediaDescr().getUnpackedValueOrDefault( sFilterNameString, OUString() );
1197
0
    const OUString aOldFilterName = GetDocProps().getUnpackedValueOrDefault( sFilterNameString, OUString() );
1198
1199
0
    if ( aFilterName == aFilterFromMediaDescr )
1200
0
    {
1201
        // preserve current settings if any
1202
        // if there no current settings and the name is the same
1203
        // as old filter name use old filter settings
1204
1205
0
        if ( aFilterFromMediaDescr == aOldFilterName )
1206
0
        {
1207
0
            ::comphelper::SequenceAsHashMap::const_iterator aIter =
1208
0
                                        GetDocProps().find( aFilterOptionsString );
1209
0
            if ( aIter != GetDocProps().end()
1210
0
              && GetMediaDescr().find( aFilterOptionsString ) == GetMediaDescr().end() )
1211
0
                GetMediaDescr()[aIter->first] = aIter->second;
1212
1213
0
            aIter = GetDocProps().find( aFilterDataString );
1214
0
            if ( aIter != GetDocProps().end()
1215
0
              && GetMediaDescr().find( aFilterDataString ) == GetMediaDescr().end() )
1216
0
                GetMediaDescr()[aIter->first] = aIter->second;
1217
0
        }
1218
0
    }
1219
0
    else
1220
0
    {
1221
0
        GetMediaDescr().erase( aFilterDataString );
1222
0
        GetMediaDescr().erase( aFilterOptionsString );
1223
1224
0
        if ( aFilterName == aOldFilterName )
1225
0
        {
1226
            // merge filter option of the document filter
1227
1228
0
            ::comphelper::SequenceAsHashMap::const_iterator aIter =
1229
0
                                GetDocProps().find( aFilterOptionsString );
1230
0
            if ( aIter != GetDocProps().end() )
1231
0
                GetMediaDescr()[aIter->first] = aIter->second;
1232
1233
0
            aIter = GetDocProps().find( aFilterDataString );
1234
0
            if ( aIter != GetDocProps().end() )
1235
0
                GetMediaDescr()[aIter->first] = aIter->second;
1236
0
        }
1237
0
    }
1238
1239
0
    uno::Reference< ui::dialogs::XFilePickerControlAccess > xExtFileDlg( pFileDlg->GetFilePicker(), uno::UNO_QUERY );
1240
0
    if ( xExtFileDlg.is() )
1241
0
    {
1242
0
        if ( SfxStoringHelper::CheckFilterOptionsAppearance( m_pOwner->GetFilterConfiguration(), aFilterName ) )
1243
0
            bUseFilterOptions = true;
1244
1245
0
        if ( ( !( nStoreMode & EXPORT_REQUESTED ) || ( nStoreMode & WIDEEXPORT_REQUESTED ) ) && bUseFilterOptions )
1246
0
        {
1247
0
            try
1248
0
            {
1249
                // for exporters: always show dialog if format uses options
1250
                // for save: show dialog if format uses options and no options given or if forced by user
1251
0
                uno::Any aVal =
1252
0
                        xExtFileDlg->getValue( ui::dialogs::ExtendedFilePickerElementIds::CHECKBOX_FILTEROPTIONS, 0 );
1253
1254
0
                aVal >>= bUseFilterOptions;
1255
0
                if ( !bUseFilterOptions )
1256
0
                    bUseFilterOptions =
1257
0
                      ( GetMediaDescr().find( aFilterDataString ) == GetMediaDescr().end()
1258
0
                      && GetMediaDescr().find( aFilterOptionsString ) == GetMediaDescr().end() );
1259
0
            }
1260
0
            catch( const lang::IllegalArgumentException& )
1261
0
            {}
1262
0
        }
1263
0
    }
1264
1265
    // merge in results of the dialog execution
1266
0
    GetMediaDescr()[u"URL"_ustr] <<= aURL.GetMainURL( INetURLObject::DecodeMechanism::NONE );
1267
0
    GetMediaDescr()[sFilterNameString] <<= aFilterName;
1268
1269
    // for Export - keep a runtime var for each document where the document was last exported to
1270
0
    if (GetStorable()->hasLocation() && (nStoreMode & EXPORT_REQUESTED))
1271
0
    {
1272
0
        uno::Sequence< beans::PropertyValue > descriptor{
1273
0
            beans::PropertyValue(u"ExportDirectory"_ustr,
1274
0
                -1, uno::Any(aURL.GetMainURL( INetURLObject::DecodeMechanism::NONE )), beans::PropertyState_DIRECT_VALUE),
1275
0
        };
1276
0
        GetModel()->setArgs(descriptor);
1277
0
    }
1278
1279
0
    return bUseFilterOptions;
1280
0
}
1281
1282
1283
bool ModelData_Impl::ShowDocumentInfoDialog()
1284
0
{
1285
0
    bool bDialogUsed = false;
1286
1287
0
    try {
1288
0
        uno::Reference< frame::XController > xController = GetModel()->getCurrentController();
1289
0
        if ( xController.is() )
1290
0
        {
1291
0
            uno::Reference< frame::XDispatchProvider > xFrameDispatch( xController->getFrame(), uno::UNO_QUERY );
1292
0
            if ( xFrameDispatch.is() )
1293
0
            {
1294
0
                util::URL aURL;
1295
0
                aURL.Complete = ".uno:SetDocumentProperties";
1296
1297
0
                uno::Reference < util::XURLTransformer > xTransformer( util::URLTransformer::create( comphelper::getProcessComponentContext() ) );
1298
0
                if ( xTransformer->parseStrict( aURL ) )
1299
0
                {
1300
0
                    uno::Reference< frame::XDispatch > xDispatch = xFrameDispatch->queryDispatch(
1301
0
                                                                                aURL,
1302
0
                                                                                u"_self"_ustr,
1303
0
                                                                                0 );
1304
0
                    if ( xDispatch.is() )
1305
0
                    {
1306
                        // tdf#119206 use (abuse?) a SynchronMode of true,
1307
                        // which will become SfxRequest::IsSynchronCall of true
1308
                        // in SfxObjectShell::ExecFile_Impl to request that we
1309
                        // do not want the properties dialog to be run async
1310
0
                        uno::Sequence< beans::PropertyValue > aProperties{
1311
0
                            comphelper::makePropertyValue(u"SynchronMode"_ustr, true)
1312
0
                        };
1313
0
                        xDispatch->dispatch(aURL, aProperties);
1314
0
                        bDialogUsed = true;
1315
0
                    }
1316
0
                }
1317
0
            }
1318
0
        }
1319
0
    }
1320
0
    catch ( const uno::Exception& )
1321
0
    {
1322
0
    }
1323
1324
0
    return bDialogUsed;
1325
0
}
1326
1327
1328
OUString ModelData_Impl::GetRecommendedExtension( const OUString& aTypeName )
1329
0
{
1330
0
    if ( aTypeName.isEmpty() )
1331
0
       return OUString();
1332
1333
0
    uno::Reference< container::XNameAccess > xTypeDetection(
1334
0
       comphelper::getProcessServiceFactory()->createInstance(u"com.sun.star.document.TypeDetection"_ustr),
1335
0
       uno::UNO_QUERY );
1336
0
    if ( xTypeDetection.is() )
1337
0
    {
1338
0
       uno::Sequence< beans::PropertyValue > aTypeNameProps;
1339
0
       if ( ( xTypeDetection->getByName( aTypeName ) >>= aTypeNameProps ) && aTypeNameProps.hasElements() )
1340
0
       {
1341
0
           ::comphelper::SequenceAsHashMap aTypeNamePropsHM( aTypeNameProps );
1342
0
           uno::Sequence< OUString > aExtensions = aTypeNamePropsHM.getUnpackedValueOrDefault(
1343
0
                                           u"Extensions"_ustr,
1344
0
                                           ::uno::Sequence< OUString >() );
1345
0
           if ( aExtensions.hasElements() )
1346
0
               return aExtensions[0];
1347
0
       }
1348
0
    }
1349
1350
0
    return OUString();
1351
0
}
1352
1353
OUString ModelData_Impl::GetRecommendedName( const OUString& aSuggestedName, const OUString& aTypeName )
1354
0
{
1355
    // the last used name might be provided by aSuggestedName from the old selection, or from the MediaDescriptor
1356
0
    if ( !aSuggestedName.isEmpty() )
1357
0
        return aSuggestedName;
1358
1359
0
    OUString aRecommendedName{ INetURLObject(GetStorable()->getLocation())
1360
0
                                   .GetLastName(INetURLObject::DecodeMechanism::WithCharset) };
1361
0
    if ( aRecommendedName.isEmpty() )
1362
0
    {
1363
0
        try {
1364
0
            uno::Reference< frame::XTitle > xTitle( GetModel(), uno::UNO_QUERY_THROW );
1365
0
            aRecommendedName = xTitle->getTitle();
1366
0
        } catch( const uno::Exception& ) {}
1367
0
    }
1368
1369
0
    if ( !aRecommendedName.isEmpty() && !aTypeName.isEmpty() )
1370
0
    {
1371
        // adjust the extension to the type
1372
0
        uno::Reference< container::XNameAccess > xTypeDetection(
1373
0
            comphelper::getProcessServiceFactory()->createInstance(u"com.sun.star.document.TypeDetection"_ustr),
1374
0
            uno::UNO_QUERY );
1375
0
        if ( xTypeDetection.is() )
1376
0
        {
1377
0
            INetURLObject aObj( rtl::Concat2View("c:/" + aRecommendedName), INetProtocol::File,
1378
0
                    INetURLObject::EncodeMechanism::All, RTL_TEXTENCODING_UTF8, FSysStyle::Dos );
1379
1380
0
            const OUString aExtension = GetRecommendedExtension( aTypeName );
1381
0
            if ( !aExtension.isEmpty() )
1382
0
                aObj.SetExtension( aExtension );
1383
1384
0
            aRecommendedName = aObj.GetLastName(INetURLObject::DecodeMechanism::WithCharset);
1385
0
        }
1386
0
    }
1387
1388
0
    return aRecommendedName;
1389
0
}
1390
1391
SfxStoringHelper::SfxStoringHelper()
1392
0
    : m_bRemote(false)
1393
0
    , m_bPreselectPassword(false)
1394
0
    , m_bDialogUsed(false)
1395
0
    , m_bSetStandardName(false)
1396
0
    , m_nStoreMode(0)
1397
0
{
1398
0
}
1399
1400
uno::Reference< container::XNameAccess > const & SfxStoringHelper::GetFilterConfiguration()
1401
0
{
1402
0
    if ( !m_xFilterCFG.is() )
1403
0
    {
1404
0
        m_xFilterCFG.set( comphelper::getProcessServiceFactory()->createInstance(u"com.sun.star.document.FilterFactory"_ustr),
1405
0
                          uno::UNO_QUERY_THROW );
1406
0
    }
1407
1408
0
    return m_xFilterCFG;
1409
0
}
1410
1411
uno::Reference< container::XContainerQuery > const & SfxStoringHelper::GetFilterQuery()
1412
0
{
1413
0
    if ( !m_xFilterQuery.is() )
1414
0
    {
1415
0
        m_xFilterQuery.set( GetFilterConfiguration(), uno::UNO_QUERY_THROW );
1416
0
    }
1417
1418
0
    return m_xFilterQuery;
1419
0
}
1420
1421
uno::Reference< css::frame::XModuleManager2 > const & SfxStoringHelper::GetModuleManager()
1422
0
{
1423
0
    if ( !m_xModuleManager.is() )
1424
0
    {
1425
0
        m_xModuleManager = frame::ModuleManager::create(
1426
0
            comphelper::getProcessComponentContext() );
1427
0
    }
1428
1429
0
    return m_xModuleManager;
1430
0
}
1431
1432
bool SfxStoringHelper::GUIStoreModel( const uno::Reference< frame::XModel2 >& xModel,
1433
                                            std::u16string_view aSlotName,
1434
                                            uno::Sequence< beans::PropertyValue >& aArgsSequence,
1435
                                            bool bPreselectPassword,
1436
                                            SignatureState const nDocumentSignatureState,
1437
                                            SignatureState const nScriptingSignatureState,
1438
                                            bool bIsAsync)
1439
0
{
1440
0
    m_xModelData = std::make_shared<ModelData_Impl>( *this, xModel, aArgsSequence );
1441
0
    m_aArgsSequence = aArgsSequence;
1442
0
    ModelData_Impl& aModelData = *m_xModelData;
1443
1444
0
    m_bDialogUsed = false;
1445
1446
0
    m_bSetStandardName = false; // can be set only for SaveAs
1447
0
    m_bPreselectPassword = bPreselectPassword;
1448
0
    m_nScriptingSignatureState = nScriptingSignatureState;
1449
1450
    // parse the slot name
1451
0
    m_bRemote = false;
1452
0
    m_nStoreMode = getStoreModeFromSlotName( aSlotName );
1453
1454
0
    if ( m_nStoreMode == SAVEASREMOTE_REQUESTED )
1455
0
    {
1456
0
        m_nStoreMode = SAVEAS_REQUESTED;
1457
0
        m_bRemote = true;
1458
0
    }
1459
1460
0
    sal_Int8 nStatusSave = STATUS_NO_ACTION;
1461
1462
0
    ::comphelper::SequenceAsHashMap::const_iterator aSaveACopyIter =
1463
0
                        aModelData.GetMediaDescr().find( u"SaveACopy"_ustr );
1464
0
    if ( aSaveACopyIter != aModelData.GetMediaDescr().end() )
1465
0
    {
1466
0
        bool bSaveACopy = false;
1467
0
        aSaveACopyIter->second >>= bSaveACopy;
1468
0
        if ( bSaveACopy )
1469
0
            m_nStoreMode = EXPORT_REQUESTED | SAVEACOPY_REQUESTED | WIDEEXPORT_REQUESTED;
1470
0
    }
1471
    // handle the special cases
1472
0
    if ( m_nStoreMode & SAVEAS_REQUESTED )
1473
0
    {
1474
0
        ::comphelper::SequenceAsHashMap::const_iterator aSaveToIter =
1475
0
                        aModelData.GetMediaDescr().find( u"SaveTo"_ustr );
1476
0
        if ( aSaveToIter != aModelData.GetMediaDescr().end() )
1477
0
        {
1478
0
            bool bWideExport = false;
1479
0
            aSaveToIter->second >>= bWideExport;
1480
0
            if ( bWideExport )
1481
0
                m_nStoreMode = EXPORT_REQUESTED | WIDEEXPORT_REQUESTED;
1482
0
        }
1483
1484
        // if saving is not acceptable the warning must be shown even in case of SaveAs operation
1485
0
        if ( ( m_nStoreMode & SAVEAS_REQUESTED ) && aModelData.CheckSaveAcceptable( STATUS_SAVEAS ) == STATUS_NO_ACTION )
1486
0
            throw task::ErrorCodeIOException(
1487
0
                u"SfxStoringHelper::GUIStoreModel: ERRCODE_IO_ABORT"_ustr,
1488
0
                uno::Reference< uno::XInterface >(), sal_uInt32(ERRCODE_IO_ABORT));
1489
0
    }
1490
0
    else if ( m_nStoreMode & SAVE_REQUESTED )
1491
0
    {
1492
        // if saving is not acceptable by the configuration the warning must be shown
1493
0
        nStatusSave = aModelData.CheckSaveAcceptable( STATUS_SAVE );
1494
1495
0
        if ( nStatusSave == STATUS_NO_ACTION )
1496
0
            throw task::ErrorCodeIOException(
1497
0
                u"SfxStoringHelper::GUIStoreModel: ERRCODE_IO_ABORT"_ustr,
1498
0
                uno::Reference< uno::XInterface >(), sal_uInt32(ERRCODE_IO_ABORT));
1499
0
        else if ( nStatusSave == STATUS_SAVE )
1500
0
        {
1501
            // check whether it is possible to use save operation
1502
0
            nStatusSave = aModelData.CheckStateForSave();
1503
0
        }
1504
1505
0
        if ( nStatusSave == STATUS_NO_ACTION )
1506
0
        {
1507
0
            throw task::ErrorCodeIOException(
1508
0
                u"SfxStoringHelper::GUIStoreModel: ERRCODE_IO_ABORT"_ustr,
1509
0
                uno::Reference< uno::XInterface >(), sal_uInt32(ERRCODE_IO_ABORT));
1510
0
        }
1511
0
        else if ( nStatusSave != STATUS_SAVE )
1512
0
        {
1513
            // this should be a usual SaveAs operation
1514
0
            m_nStoreMode = SAVEAS_REQUESTED;
1515
0
            if ( nStatusSave == STATUS_SAVEAS_STANDARDNAME )
1516
0
                m_bSetStandardName = true;
1517
0
        }
1518
0
    }
1519
1520
0
    if (!comphelper::LibreOfficeKit::isActive() && !( m_nStoreMode & EXPORT_REQUESTED ) && SfxViewShell::Current() )
1521
0
    {
1522
0
        SfxObjectShell* pDocShell = SfxViewShell::Current()->GetObjectShell();
1523
1524
        // if it is no export, warn user that the signature will be removed
1525
0
        if (  !pDocShell->IsRememberingSignature()
1526
0
           && (SignatureState::OK == nDocumentSignatureState
1527
0
           || SignatureState::INVALID == nDocumentSignatureState
1528
0
           || SignatureState::NOTVALIDATED == nDocumentSignatureState
1529
0
           || SignatureState::PARTIAL_OK == nDocumentSignatureState) )
1530
0
        {
1531
0
            std::unique_ptr<weld::MessageDialog> xMessageBox(Application::CreateMessageDialog(SfxStoringHelper::GetModelWindow(xModel),
1532
0
                                                             VclMessageType::Question, VclButtonsType::YesNo, SfxResId(RID_SVXSTR_XMLSEC_QUERY_LOSINGSIGNATURE)));
1533
0
            if (xMessageBox->run() != RET_YES)
1534
0
            {
1535
                // the user has decided not to store the document
1536
0
                throw task::ErrorCodeIOException(
1537
0
                    u"SfxStoringHelper::GUIStoreModel: ERRCODE_IO_ABORT (Preserve Signature)"_ustr,
1538
0
                    uno::Reference< uno::XInterface >(), sal_uInt32(ERRCODE_IO_ABORT));
1539
0
            }
1540
0
        }
1541
0
    }
1542
1543
0
    if ( m_nStoreMode & SAVE_REQUESTED && nStatusSave == STATUS_SAVE )
1544
0
    {
1545
        // Document properties can contain streams that should be freed before storing
1546
0
        aModelData.FreeDocumentProps();
1547
1548
0
        if ( aModelData.GetStorable2().is() )
1549
0
        {
1550
0
            try
1551
0
            {
1552
0
                aModelData.GetStorable2()->storeSelf( aModelData.GetMediaDescr().getAsConstPropertyValueList() );
1553
0
            }
1554
0
            catch (const lang::IllegalArgumentException&)
1555
0
            {
1556
0
                TOOLS_WARN_EXCEPTION("sfx.doc", "Ignoring parameters! ModelData considers this illegal");
1557
0
                aModelData.GetStorable()->store();
1558
0
            }
1559
0
        }
1560
0
        else
1561
0
        {
1562
0
            OSL_FAIL( "XStorable2 is not supported by the model!" );
1563
0
            aModelData.GetStorable()->store();
1564
0
        }
1565
1566
0
        return false;
1567
0
    }
1568
1569
    // preselect a filter for the storing process
1570
0
    uno::Sequence< beans::PropertyValue > aFilterProps = aModelData.GetPreselectedFilter_Impl( m_nStoreMode );
1571
1572
0
    DBG_ASSERT( aFilterProps.hasElements(), "No filter for storing!\n" );
1573
0
    if ( !aFilterProps.hasElements() )
1574
0
        throw task::ErrorCodeIOException(
1575
0
            u"SfxStoringHelper::GUIStoreModel: ERRCODE_IO_INVALIDPARAMETER"_ustr,
1576
0
            uno::Reference< uno::XInterface >(), sal_uInt32(ERRCODE_IO_INVALIDPARAMETER));
1577
1578
0
    ::comphelper::SequenceAsHashMap aFilterPropsHM( aFilterProps );
1579
0
    OUString aFilterName = aFilterPropsHM.getUnpackedValueOrDefault( u"Name"_ustr, OUString() );
1580
1581
0
    const OUString aFilterFromMediaDescr = aModelData.GetMediaDescr().getUnpackedValueOrDefault( aFilterNameString, OUString() );
1582
0
    const OUString aOldFilterName = aModelData.GetDocProps().getUnpackedValueOrDefault( aFilterNameString, OUString() );
1583
1584
0
    ::comphelper::SequenceAsHashMap::const_iterator aFileNameIter = aModelData.GetMediaDescr().find( u"URL"_ustr );
1585
1586
0
    bool bPDFOptions = (m_nStoreMode & PDFEXPORT_REQUESTED) && !(m_nStoreMode & PDFDIRECTEXPORT_REQUESTED);
1587
0
    bool bEPUBOptions = (m_nStoreMode & EPUBEXPORT_REQUESTED) && !(m_nStoreMode & EPUBDIRECTEXPORT_REQUESTED);
1588
0
    if ( ( m_nStoreMode & EXPORT_REQUESTED ) && (bPDFOptions || bEPUBOptions) )
1589
0
    {
1590
        // this is PDF or EPUB export, the filter options dialog should be shown before the export
1591
0
        aModelData.GetMediaDescr()[aFilterNameString] <<= aFilterName;
1592
0
        if ( aModelData.GetMediaDescr().find( u"FilterFlags"_ustr ) == aModelData.GetMediaDescr().end()
1593
0
          && aModelData.GetMediaDescr().find( aFilterOptionsString ) == aModelData.GetMediaDescr().end()
1594
0
          && aModelData.GetMediaDescr().find( aFilterDataString ) == aModelData.GetMediaDescr().end() )
1595
0
        {
1596
            // execute filter options dialog since no options are set in the media descriptor
1597
0
            if ( aModelData.ExecuteFilterDialog_Impl( aFilterName, bIsAsync ) )
1598
0
                m_bDialogUsed = true;
1599
0
        }
1600
0
    }
1601
1602
0
    if (bIsAsync)
1603
0
        return false;
1604
1605
0
    return SfxStoringHelper::FinishGUIStoreModel(aFileNameIter, aModelData, m_bRemote, m_nStoreMode, aFilterProps,
1606
0
                                                 m_bSetStandardName, m_bPreselectPassword, m_bDialogUsed,
1607
0
                                                 aFilterFromMediaDescr, aOldFilterName, aArgsSequence,
1608
0
                                                 aFilterName, nScriptingSignatureState);
1609
0
}
1610
1611
bool SfxStoringHelper::FinishGUIStoreModel(::comphelper::SequenceAsHashMap::const_iterator& aFileNameIter,
1612
                                          ModelData_Impl& aModelData, bool bRemote, sal_Int16 nStoreMode,
1613
                                          const uno::Sequence< beans::PropertyValue >& aFilterProps,
1614
                                          bool bSetStandardName, bool bPreselectPassword, bool bDialogUsed,
1615
                                          std::u16string_view aFilterFromMediaDescr,
1616
                                          std::u16string_view aOldFilterName,
1617
                                          uno::Sequence< beans::PropertyValue >& aArgsSequence,
1618
                                          OUString aFilterName,
1619
                                          SignatureState const nScriptingSignatureState)
1620
0
{
1621
0
    const OUString sFilterNameString(aFilterNameString);
1622
0
    const OUString sFilterOptionsString(aFilterOptionsString);
1623
0
    const OUString sFilterDataString(aFilterDataString);
1624
0
    bool bUseFilterOptions = false;
1625
0
    INetURLObject aURL;
1626
1627
0
    if ( aFileNameIter == aModelData.GetMediaDescr().end() )
1628
0
    {
1629
0
        sal_Int16 nDialog = SFX2_IMPL_DIALOG_CONFIG;
1630
1631
0
        if( bRemote )
1632
0
        {
1633
0
            nDialog = SFX2_IMPL_DIALOG_REMOTE;
1634
0
        }
1635
0
        else
1636
0
        {
1637
0
            ::comphelper::SequenceAsHashMap::const_iterator aDlgIter =
1638
0
                aModelData.GetMediaDescr().find( u"UseSystemDialog"_ustr );
1639
0
            if ( aDlgIter != aModelData.GetMediaDescr().end() )
1640
0
            {
1641
0
                bool bUseSystemDialog = true;
1642
0
                if ( aDlgIter->second >>= bUseSystemDialog )
1643
0
                {
1644
0
                    if ( bUseSystemDialog )
1645
0
                        nDialog = SFX2_IMPL_DIALOG_SYSTEM;
1646
0
                    else
1647
0
                        nDialog = SFX2_IMPL_DIALOG_OOO;
1648
0
                }
1649
0
            }
1650
0
        }
1651
1652
        // The Dispatch supports parameter FolderName that overwrites SuggestedSaveAsDir
1653
0
        OUString aSuggestedDir = aModelData.GetMediaDescr().getUnpackedValueOrDefault(u"FolderName"_ustr, OUString() );
1654
0
        if ( aSuggestedDir.isEmpty() )
1655
0
        {
1656
0
            aSuggestedDir = aModelData.GetMediaDescr().getUnpackedValueOrDefault(u"SuggestedSaveAsDir"_ustr, OUString() );
1657
0
            if ( aSuggestedDir.isEmpty() )
1658
0
                aSuggestedDir = aModelData.GetDocProps().getUnpackedValueOrDefault(u"SuggestedSaveAsDir"_ustr, OUString() );
1659
0
        }
1660
1661
0
        OUString aSuggestedName = aModelData.GetMediaDescr().getUnpackedValueOrDefault(u"SuggestedSaveAsName"_ustr, OUString() );
1662
0
        if ( aSuggestedName.isEmpty() )
1663
0
            aSuggestedName = aModelData.GetDocProps().getUnpackedValueOrDefault(u"SuggestedSaveAsName"_ustr, OUString() );
1664
1665
0
        css::uno::Sequence< OUString >  aDenyList;
1666
1667
0
        ::comphelper::SequenceAsHashMap::const_iterator aDenyListIter =
1668
0
            aModelData.GetMediaDescr().find( u"DenyList"_ustr );
1669
0
        if ( aDenyListIter != aModelData.GetMediaDescr().end() )
1670
0
            aDenyListIter->second >>= aDenyList;
1671
1672
0
        for (;;)
1673
0
        {
1674
            // in case the dialog is opened a second time the folder should be the same as previously navigated to by the user, not what was handed over by initial parameters
1675
0
            bUseFilterOptions = aModelData.OutputFileDialog( nStoreMode, aFilterProps, bSetStandardName, aSuggestedName, bPreselectPassword, aSuggestedDir, nDialog, aDenyList, nScriptingSignatureState );
1676
0
            if ( nStoreMode == SAVEAS_REQUESTED )
1677
0
            {
1678
                // in case of saving check filter for possible alien warning
1679
0
                const OUString aSelFilterName = aModelData.GetMediaDescr().getUnpackedValueOrDefault( sFilterNameString, OUString() );
1680
0
                sal_Int8 nStatusFilterSave = aModelData.CheckFilter( aSelFilterName );
1681
0
                if ( nStatusFilterSave == STATUS_SAVEAS_STANDARDNAME )
1682
0
                {
1683
                    // switch to best filter
1684
0
                    bSetStandardName = true;
1685
0
                }
1686
0
                else if ( nStatusFilterSave == STATUS_SAVE )
1687
0
                {
1688
                    // user confirmed alien filter or "good" filter is used
1689
0
                    break;
1690
0
                }
1691
0
            }
1692
0
            else
1693
0
                break;
1694
0
        }
1695
1696
0
        bDialogUsed = true;
1697
0
        aFileNameIter = aModelData.GetMediaDescr().find( u"URL"_ustr );
1698
0
    }
1699
0
    else
1700
0
    {
1701
        // the target file name is provided so check if new filter options
1702
        // are provided or old options can be used
1703
0
        if ( aFilterFromMediaDescr == aOldFilterName )
1704
0
        {
1705
0
            ::comphelper::SequenceAsHashMap::const_iterator aIter =
1706
0
                                            aModelData.GetDocProps().find( sFilterOptionsString );
1707
0
            if ( aIter != aModelData.GetDocProps().end()
1708
0
              && aModelData.GetMediaDescr().find( sFilterOptionsString ) == aModelData.GetMediaDescr().end() )
1709
0
                aModelData.GetMediaDescr()[aIter->first] = aIter->second;
1710
1711
0
            aIter = aModelData.GetDocProps().find( sFilterDataString );
1712
0
            if ( aIter != aModelData.GetDocProps().end()
1713
0
              && aModelData.GetMediaDescr().find( sFilterDataString ) == aModelData.GetMediaDescr().end() )
1714
0
                aModelData.GetMediaDescr()[aIter->first] = aIter->second;
1715
0
        }
1716
0
    }
1717
1718
0
    if ( aFileNameIter != aModelData.GetMediaDescr().end() )
1719
0
    {
1720
0
        OUString aFileName;
1721
0
        aFileNameIter->second >>= aFileName;
1722
0
        if (comphelper::LibreOfficeKit::isActive())
1723
0
        {
1724
            // In the LOK case, we didn't actually display any dialog yet, so invoke a callback if
1725
            // that's set.
1726
0
            OUString aNewURI;
1727
0
            if (comphelper::LibreOfficeKit::fileSaveDialog(aFileName, aNewURI))
1728
0
            {
1729
0
                if (aNewURI.isEmpty())
1730
0
                    return false;
1731
0
                aFileName = aNewURI;
1732
0
            }
1733
0
        }
1734
1735
0
        aURL.SetURL( aFileName );
1736
0
        DBG_ASSERT( aURL.GetProtocol() != INetProtocol::NotValid, "Illegal URL!" );
1737
1738
0
        ::comphelper::SequenceAsHashMap::const_iterator aIter =
1739
0
                                aModelData.GetMediaDescr().find( sFilterNameString );
1740
1741
0
        if ( aIter != aModelData.GetMediaDescr().end() )
1742
0
            aIter->second >>= aFilterName;
1743
0
        else
1744
0
            aModelData.GetMediaDescr()[sFilterNameString] <<= aFilterName;
1745
1746
0
        DBG_ASSERT( !aFilterName.isEmpty(), "Illegal filter!" );
1747
0
    }
1748
0
    else
1749
0
    {
1750
0
        SAL_WARN( "sfx.doc", "This code must be unreachable!" );
1751
0
        throw task::ErrorCodeIOException(
1752
0
            u"SfxStoringHelper::GUIStoreModel: ERRCODE_IO_INVALIDPARAMETER"_ustr,
1753
0
            uno::Reference< uno::XInterface >(), sal_uInt32(ERRCODE_IO_INVALIDPARAMETER));
1754
0
    }
1755
1756
0
    ::comphelper::SequenceAsHashMap::const_iterator aIter =
1757
0
                            aModelData.GetMediaDescr().find( u"FilterFlags"_ustr );
1758
0
    bool bFilterFlagsSet = ( aIter != aModelData.GetMediaDescr().end() );
1759
1760
    // check if the filter Dialog has not been called before
1761
0
    if( !( nStoreMode & PDFEXPORT_REQUESTED ) && !( nStoreMode & EPUBEXPORT_REQUESTED ) && !bFilterFlagsSet
1762
0
        && ( ( nStoreMode & EXPORT_REQUESTED ) || bUseFilterOptions ) )
1763
0
    {
1764
        // execute filter options dialog
1765
0
        if ( aModelData.ExecuteFilterDialog_Impl( aFilterName, false ) )
1766
0
        {
1767
0
            bDialogUsed = true;
1768
            // check if the file is a pdf or not and change the storing mode at convenience
1769
0
            if (aFilterName.endsWith("pdf_Export"))
1770
0
                nStoreMode = EXPORT_REQUESTED | PDFEXPORT_REQUESTED;
1771
0
        }
1772
0
    }
1773
1774
    // so the arguments will not change any more and can be stored to the main location
1775
0
    aArgsSequence = aModelData.GetMediaDescr().getAsConstPropertyValueList();
1776
1777
    // store the document and handle it's docinfo
1778
    // Restore when exporting (which is also done when LoKit is enable, see below).
1779
0
    const bool bRestore
1780
0
        = (nStoreMode & EXPORT_REQUESTED)
1781
0
          || ((nStoreMode & SAVEAS_REQUESTED) && comphelper::LibreOfficeKit::isActive());
1782
0
    DocumentSettingsGuard aSettingsGuard(aModelData.GetModel(), aModelData.IsRecommendReadOnly(),
1783
0
                                         bRestore);
1784
1785
    // Treat attempted PDF export like a print: update document print statistics
1786
0
    if ((nStoreMode & PDFEXPORT_REQUESTED) && SfxViewShell::Current())
1787
0
    {
1788
0
        SfxObjectShell* pDocShell = SfxViewShell::Current()->GetObjectShell();
1789
0
        const bool bWasEnableSetModified = pDocShell && pDocShell->IsEnableSetModified();
1790
0
        bool bResetESM = false;
1791
1792
0
        if (bWasEnableSetModified
1793
0
            && !officecfg::Office::Common::Print::PrintingModifiesDocument::get())
1794
0
        {
1795
0
            pDocShell->EnableSetModified(false); // don't let export mark document as modified
1796
0
            bResetESM = true;
1797
0
        }
1798
1799
0
        uno::Reference<document::XDocumentPropertiesSupplier> xDPS(
1800
0
            aModelData.GetModel(), uno::UNO_QUERY_THROW);
1801
0
        uno::Reference<document::XDocumentProperties> xDocProps(xDPS->getDocumentProperties());
1802
0
        xDocProps->setPrintDate(DateTime(DateTime::SYSTEM).GetUNODateTime());
1803
1804
0
        OUString sPrintedBy(SfxResId(STR_SFX_FILTERNAME_PDF));
1805
0
        if (pDocShell && pDocShell->IsUseUserData())
1806
0
        {
1807
0
            const OUString sFullName = SvtUserOptions().GetFullName();
1808
0
            if (!sFullName.isEmpty())
1809
0
                sPrintedBy += ": " + sFullName;
1810
0
        }
1811
0
        xDocProps->setPrintedBy(sPrintedBy);
1812
1813
0
        if (bResetESM)
1814
0
            pDocShell->EnableSetModified(true);
1815
0
    }
1816
1817
0
    OSL_ENSURE( aModelData.GetMediaDescr().find( u"Password"_ustr ) == aModelData.GetMediaDescr().end(), "The Password property of MediaDescriptor should not be used here!" );
1818
1819
    // Fetch the current view early, saving may spin the main loop, which may change the current
1820
    // view.
1821
0
    SfxViewShell* pViewShell = SfxViewShell::Current();
1822
1823
0
    if ( officecfg::Office::Common::Save::Document::EditProperty::get()
1824
0
      && ( !aModelData.GetStorable()->hasLocation()
1825
0
          || INetURLObject( aModelData.GetStorable()->getLocation() ) != aURL ) )
1826
0
    {
1827
        // this is definitely not a Save operation
1828
        // so the document info can be updated
1829
1830
        // on export document info must be preserved
1831
0
        uno::Reference<document::XDocumentPropertiesSupplier> xDPS(
1832
0
            aModelData.GetModel(), uno::UNO_QUERY_THROW);
1833
0
        uno::Reference<util::XCloneable> xCloneable(
1834
0
            xDPS->getDocumentProperties(), uno::UNO_QUERY_THROW);
1835
0
        uno::Reference<document::XDocumentProperties> xOldDocProps(
1836
0
            xCloneable->createClone(), uno::UNO_QUERY_THROW);
1837
1838
        // use dispatch API to show document info dialog
1839
0
        if ( aModelData.ShowDocumentInfoDialog() )
1840
0
            bDialogUsed = true;
1841
0
        else
1842
0
        {
1843
0
            OSL_FAIL( "Can't execute document info dialog!" );
1844
0
        }
1845
1846
0
        try {
1847
            // Document properties can contain streams that should be freed before storing
1848
0
            aModelData.FreeDocumentProps();
1849
0
            if ( nStoreMode & EXPORT_REQUESTED )
1850
0
                aModelData.GetStorable()->storeToURL( aURL.GetMainURL( INetURLObject::DecodeMechanism::NONE ), aArgsSequence );
1851
0
            else
1852
0
                aModelData.GetStorable()->storeAsURL( aURL.GetMainURL( INetURLObject::DecodeMechanism::NONE ), aArgsSequence );
1853
0
        }
1854
0
        catch( const uno::Exception& )
1855
0
        {
1856
0
            if ( nStoreMode & EXPORT_REQUESTED )
1857
0
            {
1858
0
                SetDocInfoState(aModelData.GetModel(), xOldDocProps);
1859
0
            }
1860
0
            throw;
1861
0
        }
1862
1863
0
        if ( nStoreMode & EXPORT_REQUESTED )
1864
0
        {
1865
0
            SetDocInfoState(aModelData.GetModel(), xOldDocProps);
1866
0
        }
1867
0
    }
1868
0
    else
1869
0
    {
1870
        // Document properties can contain streams that should be freed before storing
1871
0
        aModelData.FreeDocumentProps();
1872
1873
        // this is actually a save operation with different parameters
1874
        // so storeTo or storeAs without DocInfo operations are used
1875
#ifdef IOS
1876
        try
1877
        {
1878
#endif
1879
            // SaveAs in LoKit is unhelpful. It saves the document to a new path, which
1880
            // breaks the link with the storage, so new modifications can't be uploaded.
1881
0
            if ((nStoreMode & EXPORT_REQUESTED)
1882
0
                || ((nStoreMode & SAVEAS_REQUESTED) && comphelper::LibreOfficeKit::isActive()))
1883
0
                aModelData.GetStorable()->storeToURL( aURL.GetMainURL( INetURLObject::DecodeMechanism::NONE ), aArgsSequence );
1884
0
            else
1885
0
                aModelData.GetStorable()->storeAsURL( aURL.GetMainURL( INetURLObject::DecodeMechanism::NONE ), aArgsSequence );
1886
#ifdef IOS
1887
        }
1888
        catch( const uno::Exception& )
1889
        {
1890
            // When using the iOS app (and maybe the Android app), the app
1891
            // will remain blocked if we rethrow an exception.
1892
        }
1893
#endif
1894
0
    }
1895
1896
0
    if (aModelData.IsSignWithDefaultSignature())
1897
0
    {
1898
0
        auto SignWithDefaultSignature = [&]()
1899
0
        {
1900
#if HAVE_FEATURE_GPGME
1901
            auto aSigningKey = SvtUserOptions().GetSigningKey();
1902
            if (aSigningKey.isEmpty())
1903
                return;
1904
1905
            std::vector<uno::Reference<xml::crypto::XXMLSecurityContext>> xSecurityContexts{
1906
                xml::crypto::GPGSEInitializer::create(comphelper::getProcessComponentContext())
1907
                    ->createSecurityContext({}),
1908
                xml::crypto::SEInitializer::create(comphelper::getProcessComponentContext())
1909
                    ->createSecurityContext({}),
1910
            };
1911
1912
            for (const auto& xSecurityContext : xSecurityContexts)
1913
            {
1914
                if (xSecurityContext.is())
1915
                {
1916
                    css::uno::Reference<css::security::XCertificate> xCert
1917
                        = comphelper::xmlsec::FindCertInContext(xSecurityContext, aSigningKey);
1918
1919
                    if (xCert.is() && SfxViewShell::Current())
1920
                    {
1921
                        SfxObjectShell* pDocShell = SfxViewShell::Current()->GetObjectShell();
1922
                        svl::crypto::SigningContext aSigningContext;
1923
                        aSigningContext.m_xCertificate = std::move(xCert);
1924
                        bool bSigned = pDocShell->SignDocumentContentUsingCertificate(aSigningContext);
1925
                        if (bSigned && pDocShell->HasValidSignatures())
1926
                        {
1927
                            std::unique_ptr<weld::MessageDialog> xBox(
1928
                                Application::CreateMessageDialog(
1929
                                    SfxStoringHelper::GetModelWindow(aModelData.GetModel()),
1930
                                    VclMessageType::Question, VclButtonsType::YesNo,
1931
                                    SfxResId(STR_QUERY_REMEMBERSIGNATURE)));
1932
                            pDocShell->SetRememberCurrentSignature(xBox->run() == RET_YES);
1933
                        }
1934
                        return;
1935
                    }
1936
                }
1937
            }
1938
1939
            // couldn't find the specified default signing certificate!
1940
            // alert the user the document won't be signed
1941
            std::unique_ptr<weld::MessageDialog> xBox(Application::CreateMessageDialog(
1942
                SfxStoringHelper::GetModelWindow(aModelData.GetModel()),
1943
                VclMessageType::Error, VclButtonsType::Ok,
1944
                SfxResId(STR_ERROR_NOMATCHINGDEFUALTCERT)));
1945
            xBox->run();
1946
            return;
1947
#else
1948
0
            (void)aModelData;
1949
0
#endif
1950
0
        };
1951
0
        SignWithDefaultSignature();
1952
0
    }
1953
1954
    // Launch PDF viewer
1955
0
    if ( nStoreMode & PDFEXPORT_REQUESTED && !comphelper::LibreOfficeKit::isActive() )
1956
0
    {
1957
0
        FilterConfigItem aItem(u"Office.Common/Filter/PDF/Export/");
1958
0
        bool aViewPDF = aItem.ReadBool( u"ViewPDFAfterExport"_ustr, false );
1959
1960
0
        if ( aViewPDF )
1961
0
        {
1962
0
            uno::Reference<XSystemShellExecute> xSystemShellExecute(SystemShellExecute::create( ::comphelper::getProcessComponentContext() ) );
1963
0
            xSystemShellExecute->execute( aURL.GetMainURL( INetURLObject::DecodeMechanism::NONE ), u""_ustr, SystemShellExecuteFlags::URIS_ONLY );
1964
0
        }
1965
0
    }
1966
1967
0
    if ( comphelper::LibreOfficeKit::isActive() )
1968
0
    {
1969
0
        if ( pViewShell )
1970
0
        {
1971
0
            OUString sURL = aURL.GetMainURL( INetURLObject::DecodeMechanism::NONE );
1972
0
            pViewShell->libreOfficeKitViewCallback( LOK_CALLBACK_EXPORT_FILE, sURL.toUtf8() );
1973
0
        }
1974
0
    }
1975
1976
0
    return bDialogUsed;
1977
0
}
1978
1979
1980
// static
1981
bool SfxStoringHelper::CheckFilterOptionsAppearance(
1982
                                                    const uno::Reference< container::XNameAccess >& xFilterCFG,
1983
                                                    const OUString& aFilterName )
1984
0
{
1985
0
    bool bUseFilterOptions = false;
1986
1987
0
    DBG_ASSERT( xFilterCFG.is(), "No filter configuration!\n" );
1988
0
    if( xFilterCFG.is() )
1989
0
    {
1990
0
        try {
1991
0
            uno::Sequence < beans::PropertyValue > aProps;
1992
0
            uno::Any aAny = xFilterCFG->getByName( aFilterName );
1993
0
            if ( aAny >>= aProps )
1994
0
            {
1995
0
                ::comphelper::SequenceAsHashMap aPropsHM( aProps );
1996
0
                if( !aPropsHM.getUnpackedValueOrDefault( u"UIComponent"_ustr, OUString() ).isEmpty() )
1997
0
                    bUseFilterOptions = true;
1998
0
            }
1999
0
        }
2000
0
        catch( const uno::Exception& )
2001
0
        {
2002
0
        }
2003
0
    }
2004
2005
0
    return bUseFilterOptions;
2006
0
}
2007
2008
2009
// static
2010
void SfxStoringHelper::SetDocInfoState(
2011
        const uno::Reference< frame::XModel2 >& xModel,
2012
        const uno::Reference< document::XDocumentProperties>& i_xOldDocProps )
2013
0
{
2014
0
    uno::Reference<document::XDocumentPropertiesSupplier> const
2015
0
        xModelDocPropsSupplier(xModel, uno::UNO_QUERY_THROW);
2016
0
    uno::Reference<document::XDocumentProperties> const xDocPropsToFill =
2017
0
        xModelDocPropsSupplier->getDocumentProperties();
2018
0
    uno::Reference< beans::XPropertySet > const xPropSet(
2019
0
            i_xOldDocProps->getUserDefinedProperties(), uno::UNO_QUERY_THROW);
2020
2021
0
    uno::Reference< util::XModifiable > xModifiable( xModel, uno::UNO_QUERY );
2022
0
    if ( !xModifiable.is() )
2023
0
        throw uno::RuntimeException();
2024
2025
0
    bool bIsModified = xModifiable->isModified();
2026
2027
0
    try
2028
0
    {
2029
0
        uno::Reference< beans::XPropertySet > const xSet(
2030
0
                xDocPropsToFill->getUserDefinedProperties(), uno::UNO_QUERY);
2031
0
        uno::Reference< beans::XPropertyContainer > xContainer( xSet, uno::UNO_QUERY );
2032
0
        uno::Reference< beans::XPropertySetInfo > xSetInfo = xSet->getPropertySetInfo();
2033
0
        const uno::Sequence< beans::Property > lProps = xSetInfo->getProperties();
2034
0
        for (const beans::Property& rProp : lProps)
2035
0
        {
2036
0
            uno::Any aValue = xPropSet->getPropertyValue( rProp.Name );
2037
0
            if ( rProp.Attributes & css::beans::PropertyAttribute::REMOVABLE )
2038
0
            {
2039
0
                try
2040
0
                {
2041
                    // QUESTION: DefaultValue?!
2042
0
                    xContainer->addProperty( rProp.Name, rProp.Attributes, aValue );
2043
0
                }
2044
0
                catch (beans::PropertyExistException const&) {}
2045
0
                try
2046
0
                {
2047
                    // it is possible that the propertysets from XML and binary files differ; we shouldn't break then
2048
0
                    xSet->setPropertyValue( rProp.Name, aValue );
2049
0
                }
2050
0
                catch ( const uno::Exception& ) {}
2051
0
            }
2052
0
        }
2053
2054
        // sigh... have to set these manually I'm afraid... wonder why
2055
        // SfxObjectShell doesn't handle this internally, should be easier
2056
0
        xDocPropsToFill->setAuthor(i_xOldDocProps->getAuthor());
2057
0
        xDocPropsToFill->setGenerator(i_xOldDocProps->getGenerator());
2058
0
        xDocPropsToFill->setCreationDate(i_xOldDocProps->getCreationDate());
2059
0
        xDocPropsToFill->setTitle(i_xOldDocProps->getTitle());
2060
0
        xDocPropsToFill->setSubject(i_xOldDocProps->getSubject());
2061
0
        xDocPropsToFill->setDescription(i_xOldDocProps->getDescription());
2062
0
        xDocPropsToFill->setKeywords(i_xOldDocProps->getKeywords());
2063
0
        xDocPropsToFill->setModifiedBy(i_xOldDocProps->getModifiedBy());
2064
0
        xDocPropsToFill->setModificationDate(i_xOldDocProps->getModificationDate());
2065
0
        xDocPropsToFill->setPrintedBy(i_xOldDocProps->getPrintedBy());
2066
0
        xDocPropsToFill->setPrintDate(i_xOldDocProps->getPrintDate());
2067
0
        xDocPropsToFill->setAutoloadURL(i_xOldDocProps->getAutoloadURL());
2068
0
        xDocPropsToFill->setAutoloadSecs(i_xOldDocProps->getAutoloadSecs());
2069
0
        xDocPropsToFill->setDefaultTarget(i_xOldDocProps->getDefaultTarget());
2070
0
        xDocPropsToFill->setEditingCycles(i_xOldDocProps->getEditingCycles());
2071
0
        xDocPropsToFill->setEditingDuration(i_xOldDocProps->getEditingDuration());
2072
        // other attributes e.g. DocumentStatistics are not editable from dialog
2073
0
    }
2074
0
    catch (const uno::Exception&)
2075
0
    {
2076
0
        TOOLS_INFO_EXCEPTION("sfx.doc", "SetDocInfoState");
2077
0
    }
2078
2079
    // set the modified flag back if required
2080
0
    if ( bIsModified != bool(xModifiable->isModified()) )
2081
0
        xModifiable->setModified( bIsModified );
2082
0
}
2083
2084
2085
// static
2086
bool SfxStoringHelper::WarnUnacceptableFormat( const uno::Reference< frame::XModel2 >& xModel,
2087
                                                    std::u16string_view aOldUIName,
2088
                                                    std::u16string_view aExtension,
2089
                                                    const OUString& aDefExtension,
2090
                                                    bool bDefIsAlien )
2091
0
{
2092
0
    weld::Window* pWin = SfxStoringHelper::GetModelWindow(xModel);
2093
2094
0
    OUString sInfoText = SfxResId(STR_QUERY_ALIENFORMAT_TEXT);
2095
0
    sInfoText = sInfoText.replaceAll("%FORMATNAME", aOldUIName);
2096
0
    sInfoText = sInfoText.replaceAll("%EXTENSION", aExtension);
2097
2098
0
    OUString sExtension = u"ODF"_ustr;
2099
0
    OUString sQuestion = "";
2100
0
    if (bDefIsAlien) {
2101
0
        sExtension = aDefExtension.toAsciiUpperCase();
2102
0
    }
2103
0
    else
2104
0
    {
2105
0
        sQuestion = SfxResId(STR_QUERY_ALIENFORMAT_QUESTION);
2106
0
        sQuestion = sQuestion.replaceAll("%EXTENSION", aDefExtension);
2107
0
    }
2108
2109
0
    const OUString sTitle = SfxResId(STR_QUERY_ALIENFORMAT_TTITLE);
2110
0
    const OUString sYesLabel
2111
0
        = SfxResId(STR_QUERY_ALIENFORMAT_YES).replaceAll("%FORMATNAME", aOldUIName);
2112
0
    const OUString sNoLabel
2113
0
        = SfxResId(STR_QUERY_ALIENFORMAT_NO).replaceAll("%DEFAULTEXTENSION", sExtension);
2114
0
    return ConfirmationDlg::Query<officecfg::Office::Common::Save::Document::WarnAlienFormat>(
2115
0
        pWin, sTitle, sInfoText, sQuestion, sYesLabel, sNoLabel);
2116
0
}
2117
2118
uno::Reference<awt::XWindow> SfxStoringHelper::GetModelXWindow(const uno::Reference<frame::XModel2>& xModel)
2119
0
{
2120
0
    try {
2121
0
        if ( xModel.is() )
2122
0
        {
2123
0
            uno::Reference< frame::XController > xController = xModel->getCurrentController();
2124
0
            if ( xController.is() )
2125
0
            {
2126
0
                uno::Reference< frame::XFrame > xFrame = xController->getFrame();
2127
0
                if ( xFrame.is() )
2128
0
                {
2129
0
                    return xFrame->getContainerWindow();
2130
0
                }
2131
0
            }
2132
0
        }
2133
0
    }
2134
0
    catch ( const uno::Exception& )
2135
0
    {
2136
0
    }
2137
2138
0
    return uno::Reference<awt::XWindow>();
2139
0
}
2140
2141
weld::Window* SfxStoringHelper::GetModelWindow( const uno::Reference< frame::XModel2 >& xModel )
2142
0
{
2143
0
    weld::Window* pWin = nullptr;
2144
2145
0
    try
2146
0
    {
2147
0
        pWin = Application::GetFrameWeld(GetModelXWindow(xModel));
2148
0
    }
2149
0
    catch (const uno::Exception&)
2150
0
    {
2151
0
    }
2152
2153
0
    return pWin;
2154
0
}
2155
2156
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */