summaryrefslogtreecommitdiff
path: root/svx/source/gallery2/galleryfilestorage.cxx
blob: bef365a0060cc74c3700fc6b1c50ce5f5b02d1d3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include <svx/unomodel.hxx>
#include <svx/fmmodel.hxx>
#include <svx/galtheme.hxx>
#include <galobj.hxx>
#include <galleryfilestorage.hxx>
#include <svx/galleryobjectcollection.hxx>
#include <svx/gallery1.hxx>
#include "codec.hxx"
#include "gallerydrawmodel.hxx"
#include <vcl/cvtgrf.hxx>
#include <vcl/filter/SvmWriter.hxx>

#include <sal/log.hxx>

#include <com/sun/star/ucb/ContentCreationException.hpp>
#include <com/sun/star/sdbc/XResultSet.hpp>
#include <com/sun/star/ucb/XContentAccess.hpp>
#include <comphelper/fileformat.h>
#include <comphelper/graphicmimetype.hxx>
#include <comphelper/processfactory.hxx>
#include <tools/urlobj.hxx>
#include <comphelper/diagnose_ex.hxx>
#include <tools/datetime.hxx>
#include <unotools/datetime.hxx>
#include <unotools/ucbstreamhelper.hxx>
#include <unotools/streamwrap.hxx>
#include <unotools/tempfile.hxx>
#include <ucbhelper/content.hxx>
#include <tools/vcompat.hxx>

using namespace ::com::sun::star;

GalleryFileStorage::GalleryFileStorage(
    const GalleryStorageLocations& rGalleryBinaryStorageLocations,
    GalleryObjectCollection& rGalleryObjectCollection, bool bReadOnly)
    : maGalleryStorageLocations(rGalleryBinaryStorageLocations)
    , mrGalleryObjectCollection(rGalleryObjectCollection)
    , mbReadOnly(bReadOnly)
    , m_bDestDirRelative(false)
{
    ImplCreateSvDrawStorage();
}

GalleryFileStorage::~GalleryFileStorage() { clearSotStorage(); }

void GalleryFileStorage::setDestDir(const OUString& rDestDir, bool bRelative)
{
    m_aDestDir = rDestDir;
    m_bDestDirRelative = bRelative;
}

void GalleryFileStorage::clearSotStorage() { m_aSvDrawStorageRef.clear(); }

void GalleryFileStorage::ImplCreateSvDrawStorage()
{
    try
    {
        m_aSvDrawStorageRef
            = new SotStorage(false, GetSdvURL().GetMainURL(INetURLObject::DecodeMechanism::NONE),
                             mbReadOnly ? StreamMode::READ : StreamMode::STD_READWRITE);
        // #i50423# ReadOnly may not been set though the file can't be written (because of security reasons)
        if ((m_aSvDrawStorageRef->GetError() != ERRCODE_NONE) && !mbReadOnly)
            m_aSvDrawStorageRef = new SotStorage(
                false, GetSdvURL().GetMainURL(INetURLObject::DecodeMechanism::NONE),
                StreamMode::READ);
    }
    catch (const css::ucb::ContentCreationException&)
    {
        TOOLS_WARN_EXCEPTION("svx", "failed to open: " << GetSdvURL().GetMainURL(
                                                              INetURLObject::DecodeMechanism::NONE)
                                                       << "due to");
    }
}

const rtl::Reference<SotStorage>& GalleryFileStorage::GetSvDrawStorage() const
{
    return m_aSvDrawStorageRef;
}

bool GalleryFileStorage::implWrite(const GalleryTheme& rTheme, const GalleryThemeEntry* pThm)
{
    INetURLObject aPathURL(GetThmURL());

    aPathURL.removeSegment();
    aPathURL.removeFinalSlash();

    DBG_ASSERT(aPathURL.GetProtocol() != INetProtocol::NotValid, "invalid URL");

    if (FileExists(aPathURL) || CreateDir(aPathURL))
    {
#ifdef UNX
        std::unique_ptr<SvStream> pOStm(::utl::UcbStreamHelper::CreateStream(
            GetThmURL().GetMainURL(INetURLObject::DecodeMechanism::NONE),
            StreamMode::WRITE | StreamMode::COPY_ON_SYMLINK | StreamMode::TRUNC));
#else
        std::unique_ptr<SvStream> pOStm(::utl::UcbStreamHelper::CreateStream(
            GetThmURL().GetMainURL(INetURLObject::DecodeMechanism::NONE),
            StreamMode::WRITE | StreamMode::TRUNC));
#endif

        if (pOStm)
        {
            writeGalleryTheme(*pOStm, rTheme, pThm);
            pOStm.reset();
            return true;
        }

        return false;
    }
    return true;
}

void GalleryFileStorage::insertObject(const SgaObject& rObj, GalleryObject* pFoundEntry,
                                      sal_uInt32 nInsertPos)
{
    if (pFoundEntry)
    {
        GalleryObject aNewEntry;

        // update title of new object if necessary
        if (rObj.GetTitle().isEmpty())
        {
            std::unique_ptr<SgaObject> pOldObj(implReadSgaObject(pFoundEntry));

            if (pOldObj)
            {
                const_cast<SgaObject&>(rObj).SetTitle(pOldObj->GetTitle());
            }
        }
        else if (rObj.GetTitle() == "__<empty>__")
            const_cast<SgaObject&>(rObj).SetTitle("");

        implWriteSgaObject(rObj, nInsertPos, &aNewEntry);
        pFoundEntry->nOffset = aNewEntry.nOffset;
    }
    else
        implWriteSgaObject(rObj, nInsertPos, nullptr);
}

void GalleryFileStorage::removeObject(const std::unique_ptr<GalleryObject>& pEntry)
{
    if (mrGalleryObjectCollection.getObjectList().empty())
        KillFile(GetSdgURL());

    if (SgaObjKind::SvDraw == pEntry->eObjKind)
        GetSvDrawStorage()->Remove(
            pEntry->m_oStorageUrl->GetMainURL(INetURLObject::DecodeMechanism::NONE));
}

std::unique_ptr<SgaObject> GalleryFileStorage::implReadSgaObject(GalleryObject const* pEntry)
{
    std::unique_ptr<SgaObject> pSgaObj;

    if (pEntry)
    {
        std::unique_ptr<SvStream> pIStm(::utl::UcbStreamHelper::CreateStream(
            GetSdgURL().GetMainURL(INetURLObject::DecodeMechanism::NONE), StreamMode::READ));

        if (pIStm)
        {
            sal_uInt32 nInventor;

            // Check to ensure that the file is a valid SGA file
            pIStm->Seek(pEntry->nOffset);
            pIStm->ReadUInt32(nInventor);

            if (nInventor == COMPAT_FORMAT('S', 'G', 'A', '3'))
            {
                pIStm->Seek(pEntry->nOffset);

                switch (pEntry->eObjKind)
                {
                    case SgaObjKind::Bitmap:
                        pSgaObj.reset(new SgaObjectBmp());
                        break;
                    case SgaObjKind::Animation:
                        pSgaObj.reset(new SgaObjectAnim());
                        break;
                    case SgaObjKind::Inet:
                        pSgaObj.reset(new SgaObjectINet());
                        break;
                    case SgaObjKind::SvDraw:
                        pSgaObj.reset(new SgaObjectSvDraw());
                        break;
                    case SgaObjKind::Sound:
                        pSgaObj.reset(new SgaObjectSound());
                        break;

                    default:
                        break;
                }

                if (pSgaObj)
                {
                    ReadSgaObject(*pIStm, *pSgaObj);
                    pSgaObj->ImplUpdateURL(*pEntry->m_oStorageUrl);
                }
            }
        }
    }

    return pSgaObj;
}

bool GalleryFileStorage::implWriteSgaObject(const SgaObject& rObj, sal_uInt32 nPos,
                                            GalleryObject* pExistentEntry)
{
    std::unique_ptr<SvStream> pOStm(::utl::UcbStreamHelper::CreateStream(
        GetSdgURL().GetMainURL(INetURLObject::DecodeMechanism::NONE), StreamMode::WRITE));
    bool bRet = false;

    if (pOStm)
    {
        const sal_uInt32 nOffset = pOStm->Seek(STREAM_SEEK_TO_END);

        rObj.WriteData(*pOStm, m_aDestDir);

        if (!pOStm->GetError())
        {
            GalleryObject* pEntry;

            if (!pExistentEntry)
            {
                pEntry = new GalleryObject;
                if (nPos < mrGalleryObjectCollection.size())
                {
                    mrGalleryObjectCollection.getObjectList().emplace(
                        mrGalleryObjectCollection.getObjectList().begin() + nPos, pEntry);
                }
                else
                    mrGalleryObjectCollection.getObjectList().emplace_back(pEntry);
            }
            else
                pEntry = pExistentEntry;

            pEntry->m_oStorageUrl = rObj.GetURL();

            pEntry->nOffset = nOffset;
            pEntry->eObjKind = rObj.GetObjKind();
            bRet = true;
        }
    }

    return bRet;
}

bool GalleryFileStorage::readModel(const GalleryObject* pObject, SdrModel& rModel)
{
    rtl::Reference<SotStorage> xSotStorage(GetSvDrawStorage());
    bool bRet = false;
    const INetURLObject aURL(ImplGetURL(pObject));

    if (xSotStorage.is())
    {
        const OUString aStreamName(GetSvDrawStreamNameFromURL(aURL));
        rtl::Reference<SotStorageStream> xInputStream(
            xSotStorage->OpenSotStream(aStreamName, StreamMode::READ));

        if (xInputStream.is() && !xInputStream->GetError())
        {
            xInputStream->SetBufferSize(STREAMBUF_SIZE);
            bRet = GallerySvDrawImport(*xInputStream, rModel);
            xInputStream->SetBufferSize(0);
        }
    }
    return bRet;
}

SgaObjectSvDraw GalleryFileStorage::insertModel(const FmFormModel& rModel,
                                                const INetURLObject& rUserURL)
{
    INetURLObject aURL(implCreateUniqueURL(SgaObjKind::SvDraw, rUserURL));
    rtl::Reference<SotStorage> xSotStorage(GetSvDrawStorage());
    bool bRet = false;

    if (xSotStorage.is())
    {
        const OUString aStreamName(GetSvDrawStreamNameFromURL(aURL));
        rtl::Reference<SotStorageStream> xOutputStream(
            xSotStorage->OpenSotStream(aStreamName, StreamMode::WRITE | StreamMode::TRUNC));

        if (xOutputStream.is() && !xOutputStream->GetError())
        {
            SvMemoryStream aMemoryStream(65535, 65535);
            FmFormModel* pFormModel = const_cast<FmFormModel*>(&rModel);

            pFormModel->BurnInStyleSheetAttributes();

            {
                uno::Reference<io::XOutputStream> xDocOut(
                    new utl::OOutputStreamWrapper(aMemoryStream));

                if (xDocOut.is())
                    (void)SvxDrawingLayerExport(pFormModel, xDocOut);
            }

            aMemoryStream.Seek(0);

            xOutputStream->SetBufferSize(16348);
            GalleryCodec aCodec(*xOutputStream);
            aCodec.Write(aMemoryStream);

            xOutputStream->SetBufferSize(0);
            xOutputStream->Commit();
            bRet = !xOutputStream->GetError();
        }
    }
    if (bRet)
    {
        SgaObjectSvDraw aObjSvDraw(rModel, aURL);
        return aObjSvDraw;
    }
    return SgaObjectSvDraw();
}

bool GalleryFileStorage::readModelStream(const GalleryObject* pObject,
                                         tools::SvRef<SotTempStream> const& rxModelStream)
{
    const INetURLObject aURL(ImplGetURL(pObject));
    rtl::Reference<SotStorage> xSotStorage(GetSvDrawStorage());
    bool bRet = false;

    if (xSotStorage.is())
    {
        const OUString aStreamName(GetSvDrawStreamNameFromURL(aURL));
        rtl::Reference<SotStorageStream> xInputStream(
            xSotStorage->OpenSotStream(aStreamName, StreamMode::READ));

        if (xInputStream.is() && !xInputStream->GetError())
        {
            sal_uInt32 nVersion = 0;

            xInputStream->SetBufferSize(16348);

            if (GalleryCodec::IsCoded(*xInputStream, nVersion))
            {
                SvxGalleryDrawModel aModel;

                if (aModel.GetModel())
                {
                    if (GallerySvDrawImport(*xInputStream, *aModel.GetModel()))
                    {
                        aModel.GetModel()->BurnInStyleSheetAttributes();

                        {
                            uno::Reference<io::XOutputStream> xDocOut(
                                new utl::OOutputStreamWrapper(*rxModelStream));

                            SvxDrawingLayerExport(aModel.GetModel(), xDocOut);
                        }
                    }

                    bRet = (rxModelStream->GetError() == ERRCODE_NONE);
                }
            }

            xInputStream->SetBufferSize(0);
        }
    }
    return bRet;
}

SgaObjectSvDraw
GalleryFileStorage::insertModelStream(const tools::SvRef<SotTempStream>& rxModelStream,
                                      const INetURLObject& rUserURL)
{
    INetURLObject aURL(implCreateUniqueURL(SgaObjKind::SvDraw, rUserURL));
    rtl::Reference<SotStorage> xSotStorage(GetSvDrawStorage());

    if (xSotStorage.is())
    {
        const OUString aStreamName(GetSvDrawStreamNameFromURL(aURL));
        rtl::Reference<SotStorageStream> xOutputStream(
            xSotStorage->OpenSotStream(aStreamName, StreamMode::WRITE | StreamMode::TRUNC));

        if (xOutputStream.is() && !xOutputStream->GetError())
        {
            GalleryCodec aCodec(*xOutputStream);

            xOutputStream->SetBufferSize(16348);
            aCodec.Write(*rxModelStream);

            if (!xOutputStream->GetError())
            {
                xOutputStream->Seek(0);
                SgaObjectSvDraw aObjSvDraw(*xOutputStream, aURL);
                return aObjSvDraw;
            }
        }
    }
    return SgaObjectSvDraw();
}

INetURLObject GalleryFileStorage::implCreateUniqueURL(SgaObjKind eObjKind,
                                                      const INetURLObject& rUserURL,
                                                      ConvertDataFormat nFormat)
{
    INetURLObject aDir(rUserURL);
    INetURLObject aInfoFileURL(rUserURL);
    INetURLObject aNewURL;
    sal_uInt32 nNextNumber = 1999;
    char const* pExt = nullptr;
    bool bExists;

    aDir.Append(u"dragdrop");
    CreateDir(aDir);

    aInfoFileURL.Append(u"sdddndx1");

    // read next possible number
    if (FileExists(aInfoFileURL))
    {
        std::unique_ptr<SvStream> pIStm(::utl::UcbStreamHelper::CreateStream(
            aInfoFileURL.GetMainURL(INetURLObject::DecodeMechanism::NONE), StreamMode::READ));

        if (pIStm)
        {
            pIStm->ReadUInt32(nNextNumber);
        }
    }

    pExt = comphelper::GraphicMimeTypeHelper::GetExtensionForConvertDataFormat(nFormat);

    do
    {
        // get URL
        if (SgaObjKind::SvDraw == eObjKind)
        {
            OUString aFileName = "gallery/svdraw/dd" + OUString::number(++nNextNumber % 99999999);
            aNewURL = INetURLObject(aFileName, INetProtocol::PrivSoffice);

            bExists = false;

            for (auto const& pObject : mrGalleryObjectCollection.getObjectList())
            {
                if (*pObject->m_oStorageUrl == aNewURL)
                {
                    bExists = true;
                    break;
                }
            }
        }
        else
        {
            OUString aFileName = "dd" + OUString::number(++nNextNumber % 999999);

            if (pExt)
                aFileName += OUString(pExt, strlen(pExt), RTL_TEXTENCODING_ASCII_US);

            aNewURL = aDir;
            aNewURL.Append(aFileName);

            bExists = FileExists(aNewURL);
        }
    } while (bExists);

    // write updated number
    std::unique_ptr<SvStream> pOStm(::utl::UcbStreamHelper::CreateStream(
        aInfoFileURL.GetMainURL(INetURLObject::DecodeMechanism::NONE), StreamMode::WRITE));

    if (pOStm)
    {
        pOStm->WriteUInt32(nNextNumber);
    }

    return aNewURL;
}

SgaObjectBmp GalleryFileStorage::insertGraphic(const Graphic& rGraphic, const GfxLink& aGfxLink,
                                               const ConvertDataFormat& nExportFormat,
                                               const INetURLObject& rUserURL)
{
    const INetURLObject aURL(implCreateUniqueURL(SgaObjKind::Bitmap, rUserURL, nExportFormat));
    std::unique_ptr<SvStream> pOStm(
        ::utl::UcbStreamHelper::CreateStream(aURL.GetMainURL(INetURLObject::DecodeMechanism::NONE),
                                             StreamMode::WRITE | StreamMode::TRUNC));
    bool bRet = false;

    if (pOStm)
    {
        pOStm->SetVersion(SOFFICE_FILEFORMAT_50);

        if (ConvertDataFormat::SVM == nExportFormat)
        {
            GDIMetaFile aMtf(rGraphic.GetGDIMetaFile());

            SvmWriter aWriter(*pOStm);
            aWriter.Write(aMtf);
            bRet = (pOStm->GetError() == ERRCODE_NONE);
        }
        else
        {
            if (aGfxLink.GetDataSize() && aGfxLink.GetData())
            {
                pOStm->WriteBytes(aGfxLink.GetData(), aGfxLink.GetDataSize());
                bRet = (pOStm->GetError() == ERRCODE_NONE);
            }
            else
                bRet = (GraphicConverter::Export(*pOStm, rGraphic, nExportFormat) == ERRCODE_NONE);
        }

        pOStm.reset();
    }
    if (bRet)
    {
        const SgaObjectBmp aObjBmp(aURL);
        return aObjBmp;
    }
    return SgaObjectBmp();
}

SgaObjectSvDraw GalleryFileStorage::updateSvDrawObject(const GalleryObject* pEntry)
{
    if (GetSvDrawStorage().is())
    {
        const OUString aStmName(GetSvDrawStreamNameFromURL(*pEntry->m_oStorageUrl));
        rtl::Reference<SotStorageStream> pIStm
            = GetSvDrawStorage()->OpenSotStream(aStmName, StreamMode::READ);

        if (pIStm.is() && !pIStm->GetError())
        {
            pIStm->SetBufferSize(16384);

            SgaObjectSvDraw aNewObj(*pIStm, *pEntry->m_oStorageUrl);

            pIStm->SetBufferSize(0);

            return aNewObj;
        }
    }
    return SgaObjectSvDraw();
}

void GalleryFileStorage::updateTheme()
{
    ::utl::TempFileNamed aTmp;
    INetURLObject aInURL(GetSdgURL());
    INetURLObject aTmpURL(aTmp.GetURL());

    DBG_ASSERT(aInURL.GetProtocol() != INetProtocol::NotValid, "invalid URL");
    DBG_ASSERT(aTmpURL.GetProtocol() != INetProtocol::NotValid, "invalid URL");

    std::unique_ptr<SvStream> pIStm(::utl::UcbStreamHelper::CreateStream(
        aInURL.GetMainURL(INetURLObject::DecodeMechanism::NONE), StreamMode::READ));
    std::unique_ptr<SvStream> pTmpStm(::utl::UcbStreamHelper::CreateStream(
        aTmpURL.GetMainURL(INetURLObject::DecodeMechanism::NONE),
        StreamMode::WRITE | StreamMode::TRUNC));

    if (pIStm && pTmpStm)
    {
        for (const auto& i : mrGalleryObjectCollection.getObjectList())
        {
            GalleryObject* pEntry = i.get();
            std::unique_ptr<SgaObject> pObj;

            switch (pEntry->eObjKind)
            {
                case SgaObjKind::Bitmap:
                    pObj.reset(new SgaObjectBmp());
                    break;
                case SgaObjKind::Animation:
                    pObj.reset(new SgaObjectAnim());
                    break;
                case SgaObjKind::Inet:
                    pObj.reset(new SgaObjectINet());
                    break;
                case SgaObjKind::SvDraw:
                    pObj.reset(new SgaObjectSvDraw());
                    break;
                case SgaObjKind::Sound:
                    pObj.reset(new SgaObjectSound());
                    break;

                default:
                    break;
            }

            if (pObj)
            {
                pIStm->Seek(pEntry->nOffset);
                ReadSgaObject(*pIStm, *pObj);
                pEntry->nOffset = pTmpStm->Tell();
                WriteSgaObject(*pTmpStm, *pObj);
            }
        }
    }
    else
    {
        OSL_FAIL("File(s) could not be opened");
    }

    pIStm.reset();
    pTmpStm.reset();

    CopyFile(aTmpURL, aInURL);
    KillFile(aTmpURL);

    ErrCode nStorErr = ERRCODE_NONE;

    try
    {
        rtl::Reference<SotStorage> aTempStorageRef(
            new SotStorage(false, aTmpURL.GetMainURL(INetURLObject::DecodeMechanism::NONE),
                           StreamMode::STD_READWRITE));
        GetSvDrawStorage()->CopyTo(aTempStorageRef.get());
        nStorErr = GetSvDrawStorage()->GetError();
    }
    catch (const css::ucb::ContentCreationException&)
    {
        TOOLS_WARN_EXCEPTION("svx", "failed to open: "
                                        << aTmpURL.GetMainURL(INetURLObject::DecodeMechanism::NONE)
                                        << "due to");
        nStorErr = ERRCODE_IO_GENERAL;
    }

    if (nStorErr == ERRCODE_NONE)
    {
        clearSotStorage();
        CopyFile(aTmpURL, GetSdvURL());
        ImplCreateSvDrawStorage();
    }

    KillFile(aTmpURL);
}

void GalleryFileStorage::insertFileOrDirURL(const INetURLObject& rFileOrDirURL,
                                            std::vector<INetURLObject>& rURLVector)
{
    INetURLObject aURL;
    try
    {
        ::ucbhelper::Content aCnt(rFileOrDirURL.GetMainURL(INetURLObject::DecodeMechanism::NONE),
                                  uno::Reference<ucb::XCommandEnvironment>(),
                                  comphelper::getProcessComponentContext());
        bool bFolder = false;

        aCnt.getPropertyValue("IsFolder") >>= bFolder;

        if (bFolder)
        {
            uno::Sequence<OUString> aProps{ "Url" };
            uno::Reference<sdbc::XResultSet> xResultSet(
                aCnt.createCursor(aProps, ::ucbhelper::INCLUDE_DOCUMENTS_ONLY));
            uno::Reference<ucb::XContentAccess> xContentAccess(xResultSet, uno::UNO_QUERY);
            if (xContentAccess.is())
            {
                while (xResultSet->next())
                {
                    aURL.SetSmartURL(xContentAccess->queryContentIdentifierString());
                    rURLVector.push_back(aURL);
                }
            }
        }
        else
            rURLVector.push_back(rFileOrDirURL);
    }
    catch (const ucb::ContentCreationException&)
    {
    }
    catch (const uno::RuntimeException&)
    {
    }
    catch (const uno::Exception&)
    {
    }
}

SvStream& GalleryFileStorage::writeGalleryTheme(SvStream& rOStm, const GalleryTheme& rTheme,
                                                const GalleryThemeEntry* pThm)
{
    const INetURLObject rRelURL1 = rTheme.GetParent()->GetRelativeURL();
    const INetURLObject rRelURL2 = rTheme.GetParent()->GetUserURL();
    const sal_uInt32 rId = rTheme.GetId();
    sal_uInt32 nCount = mrGalleryObjectCollection.size();
    bool bRel;

    rOStm.WriteUInt16(0x0004);
    write_uInt16_lenPrefixed_uInt8s_FromOUString(rOStm, pThm->GetThemeName(),
                                                 RTL_TEXTENCODING_UTF8);
    rOStm.WriteUInt32(nCount);
    rOStm.WriteUInt16(RTL_TEXTENCODING_UTF8); // unused on reading

    for (sal_uInt32 i = 0; i < nCount; i++)
    {
        const GalleryObject* pObj = mrGalleryObjectCollection.getForPosition(i);
        OUString aPath;

        if (SgaObjKind::SvDraw == pObj->eObjKind)
        {
            aPath = GetSvDrawStreamNameFromURL(*pObj->m_oStorageUrl);
            bRel = false;
        }
        else
        {
            aPath = pObj->m_oStorageUrl->GetMainURL(INetURLObject::DecodeMechanism::NONE);
            aPath = aPath.copy(
                0, std::min(rRelURL1.GetMainURL(INetURLObject::DecodeMechanism::NONE).getLength(),
                            aPath.getLength()));
            bRel = aPath == rRelURL1.GetMainURL(INetURLObject::DecodeMechanism::NONE);

            if (bRel
                && (pObj->m_oStorageUrl->GetMainURL(INetURLObject::DecodeMechanism::NONE)
                        .getLength()
                    > (rRelURL1.GetMainURL(INetURLObject::DecodeMechanism::NONE).getLength() + 1)))
            {
                aPath = pObj->m_oStorageUrl->GetMainURL(INetURLObject::DecodeMechanism::NONE);
                aPath = aPath.copy(
                    std::min(rRelURL1.GetMainURL(INetURLObject::DecodeMechanism::NONE).getLength(),
                             aPath.getLength()));
            }
            else
            {
                aPath = pObj->m_oStorageUrl->GetMainURL(INetURLObject::DecodeMechanism::NONE);
                aPath = aPath.copy(
                    0,
                    std::min(rRelURL2.GetMainURL(INetURLObject::DecodeMechanism::NONE).getLength(),
                             aPath.getLength()));
                bRel = aPath == rRelURL2.GetMainURL(INetURLObject::DecodeMechanism::NONE);

                if (bRel
                    && (pObj->m_oStorageUrl->GetMainURL(INetURLObject::DecodeMechanism::NONE)
                            .getLength()
                        > (rRelURL2.GetMainURL(INetURLObject::DecodeMechanism::NONE).getLength()
                           + 1)))
                {
                    aPath = pObj->m_oStorageUrl->GetMainURL(INetURLObject::DecodeMechanism::NONE);
                    aPath = aPath.copy(std::min(
                        rRelURL2.GetMainURL(INetURLObject::DecodeMechanism::NONE).getLength(),
                        aPath.getLength()));
                }
                else
                    aPath = pObj->m_oStorageUrl->GetMainURL(INetURLObject::DecodeMechanism::NONE);
            }
        }

        if (!m_aDestDir.isEmpty())
        {
            bool aFound = aPath.indexOf(m_aDestDir) != -1;
            aPath = aPath.replaceFirst(m_aDestDir, "");
            if (aFound)
                bRel = m_bDestDirRelative;
            else
                SAL_WARN("svx", "failed to replace destdir of '" << m_aDestDir << "' in '" << aPath
                                                                 << "'");
        }

        rOStm.WriteBool(bRel);
        write_uInt16_lenPrefixed_uInt8s_FromOUString(rOStm, aPath, RTL_TEXTENCODING_UTF8);
        rOStm.WriteUInt32(pObj->nOffset).WriteUInt16(static_cast<sal_uInt16>(pObj->eObjKind));
    }

    // more recently, a 512-byte reserve buffer is written,
    // to recognize them two sal_uInt32-Ids will be written.
    rOStm.WriteUInt32(COMPAT_FORMAT('G', 'A', 'L', 'R'))
        .WriteUInt32(COMPAT_FORMAT('E', 'S', 'R', 'V'));

    const sal_uInt64 nReservePos = rOStm.Tell();
    std::unique_ptr<VersionCompatWrite> pCompat(new VersionCompatWrite(rOStm, 2));

    rOStm.WriteUInt32(rId).WriteBool(pThm->IsNameFromResource()); // From version 2 and up

    pCompat.reset();

    // Fill the rest of the buffer.
    const tools::Long nRest
        = std::max(tools::Long(512 - (rOStm.Tell() - nReservePos)), tools::Long(0));

    if (nRest)
    {
        std::unique_ptr<char[]> pReserve(new char[nRest]);
        memset(pReserve.get(), 0, nRest);
        rOStm.WriteBytes(pReserve.get(), nRest);
    }

    return rOStm;
}

DateTime GalleryFileStorage::getModificationDate() const
{
    ::ucbhelper::Content aCnt(GetThmURL().GetMainURL(INetURLObject::DecodeMechanism::NONE),
                              uno::Reference<ucb::XCommandEnvironment>(),
                              comphelper::getProcessComponentContext());
    util::DateTime aDateTimeModified;
    DateTime aDateTime(DateTime::EMPTY);

    aCnt.getPropertyValue("DateModified") >>= aDateTimeModified;
    ::utl::typeConvert(aDateTimeModified, aDateTime);

    return aDateTime;
}

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