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

#include <sal/log.hxx>
#include <rtl/tencinfo.h>
#include <comphelper/processfactory.hxx>
#include <comphelper/propertyvalue.hxx>
#include <comphelper/xmlencode.hxx>
#include <o3tl/safeint.hxx>
#include <osl/file.hxx>
#include <unotools/ucbstreamhelper.hxx>
#include <sfx2/frmhtmlw.hxx>
#include <sfx2/progress.hxx>
#include <utility>
#include <svx/svditer.hxx>
#include <editeng/eeitem.hxx>
#include <editeng/outlobj.hxx>
#include <svtools/htmlout.hxx>
#include <editeng/editeng.hxx>
#include <editeng/wghtitem.hxx>
#include <editeng/udlnitem.hxx>
#include <editeng/postitem.hxx>
#include <editeng/crossedoutitem.hxx>
#include <editeng/flditem.hxx>
#include <editeng/frmdiritem.hxx>
#include <svx/svdoutl.hxx>
#include <svx/svdogrp.hxx>
#include <svx/svdotable.hxx>
#include <tools/urlobj.hxx>
#include <svtools/sfxecode.hxx>
#include <tools/debug.hxx>

#include <drawdoc.hxx>
#include <DrawDocShell.hxx>
#include <Outliner.hxx>
#include <sdpage.hxx>
#include <strings.hrc>
#include <strings.hxx>
#include <sdresid.hxx>

using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::frame;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::document;

using namespace sdr::table;

namespace {

// Helper class for the simple creation of files local/remote
class EasyFile
{
private:
    std::unique_ptr<SvStream> pOStm;
    bool        bOpen;

public:

    EasyFile();
    ~EasyFile();

    ErrCode   createStream( const OUString& rUrl, SvStream*& rpStr );
    void      createFileName(  const OUString& rUrl, OUString& rFileName );
    void      close();
};

// create area for a circle; we expect pixel coordinates
OUString ColorToHTMLString( Color aColor )
{
    static const char hex[] = "0123456789ABCDEF";
    OUStringBuffer aStr( "#xxxxxx" );
    aStr[1] = hex[(aColor.GetRed() >> 4) & 0xf];
    aStr[2] = hex[aColor.GetRed() & 0xf];
    aStr[3] = hex[(aColor.GetGreen() >> 4) & 0xf];
    aStr[4] = hex[aColor.GetGreen() & 0xf];
    aStr[5] = hex[(aColor.GetBlue() >> 4) & 0xf];
    aStr[6] = hex[aColor.GetBlue() & 0xf];

    return aStr.makeStringAndClear();
}

} //namespace

// Helper class for the embedding of text attributes into the html output
class HtmlState
{
private:
    bool mbColor;
    bool mbWeight;
    bool mbItalic;
    bool mbUnderline;
    bool mbStrike;
    bool mbLink;
    Color maColor;
    Color maDefColor;
    OUString maLink;
    OUString maTarget;

public:
    explicit HtmlState( Color aDefColor );

    OUString SetWeight( bool bWeight );
    OUString SetItalic( bool bItalic );
    OUString SetUnderline( bool bUnderline );
    OUString SetColor( Color aColor );
    OUString SetStrikeout( bool bStrike );
    OUString SetLink( const OUString& aLink, const OUString& aTarget );
    OUString Flush();
};

// close all still open tags
OUString HtmlState::Flush()
{
    OUString aStr = SetWeight(false)
                  + SetItalic(false)
                  + SetUnderline(false)
                  + SetStrikeout(false)
                  + SetColor(maDefColor)
                  + SetLink("","");

    return aStr;
}

// c'tor with default color for the page
HtmlState::HtmlState( Color aDefColor )
  : mbColor(false),
    mbWeight(false),
    mbItalic(false),
    mbUnderline(false),
    mbStrike(false),
    mbLink(false),
    maDefColor(aDefColor)
{
}

// enables/disables bold print
OUString HtmlState::SetWeight( bool bWeight )
{
    OUString aStr;

    if(bWeight && !mbWeight)
        aStr = "<b>";
    else if(!bWeight && mbWeight)
        aStr = "</b>";

    mbWeight = bWeight;
    return aStr;
}

// enables/disables italic

OUString HtmlState::SetItalic( bool bItalic )
{
    OUString aStr;

    if(bItalic && !mbItalic)
        aStr = "<i>";
    else if(!bItalic && mbItalic)
        aStr = "</i>";

    mbItalic = bItalic;
    return aStr;
}

// enables/disables underlines

OUString HtmlState::SetUnderline( bool bUnderline )
{
    OUString aStr;

    if(bUnderline && !mbUnderline)
        aStr = "<u>";
    else if(!bUnderline && mbUnderline)
        aStr = "</u>";

    mbUnderline = bUnderline;
    return aStr;
}

// enables/disables strike through
OUString HtmlState::SetStrikeout( bool bStrike )
{
    OUString aStr;

    if(bStrike && !mbStrike)
        aStr = "<strike>";
    else if(!bStrike && mbStrike)
        aStr = "</strike>";

    mbStrike = bStrike;
    return aStr;
}

// Sets the specified text color
OUString HtmlState::SetColor( Color aColor )
{
    OUString aStr;

    if(mbColor && aColor == maColor)
        return aStr;

    if(mbColor)
    {
        aStr = "</font>";
        mbColor = false;
    }

    if(aColor != maDefColor)
    {
        maColor = aColor;
        aStr += "<font color=\"" + ColorToHTMLString(aColor) + "\">";
        mbColor = true;
    }

    return aStr;
}

// enables/disables a hyperlink
OUString HtmlState::SetLink( const OUString& aLink, const OUString& aTarget )
{
    OUString aStr;

    if(mbLink&&maLink == aLink&&maTarget==aTarget)
        return aStr;

    if(mbLink)
    {
        aStr = "</a>";
        mbLink = false;
    }

    if (!aLink.isEmpty())
    {
        aStr += "<a href=\"" + comphelper::string::encodeForXml(aLink);
        if (!aTarget.isEmpty())
        {
            aStr += "\" target=\"" + comphelper::string::encodeForXml(aTarget);
        }
        aStr += "\">";
        mbLink = true;
        maLink = aLink;
        maTarget = aTarget;
    }

    return aStr;
}

namespace
{

OUString getParagraphStyle( const SdrOutliner* pOutliner, sal_Int32 nPara )
{
    SfxItemSet aParaSet( pOutliner->GetParaAttribs( nPara ) );

    OUString sStyle;

    if( aParaSet.GetItem<SvxFrameDirectionItem>( EE_PARA_WRITINGDIR )->GetValue() == SvxFrameDirection::Horizontal_RL_TB )
    {

        sStyle = "direction: rtl;";
    }
    else
    {
        // This is the default so don't write it out
        // sStyle += "direction: ltr;";
    }
    return sStyle;
}

void lclAppendStyle(OUStringBuffer& aBuffer, std::u16string_view aTag, std::u16string_view aStyle)
{
    if (aStyle.empty())
        aBuffer.append(OUString::Concat("<") + aTag + ">");
    else
        aBuffer.append(OUString::Concat("<") + aTag + " style=\"" + aStyle + "\">");
}

// Depending on the attributes of the specified set and the specified
// HtmlState, it creates the needed html tags in order to get the
// attributes
OUString TextAttribToHTMLString( SfxItemSet const * pSet, HtmlState* pState )
{
    OUStringBuffer aStr;

    if(nullptr == pSet)
        return OUString();

    OUString aLink, aTarget;
    if ( pSet->GetItemState( EE_FEATURE_FIELD ) == SfxItemState::SET )
    {
        const SvxFieldItem* pItem = pSet->GetItem<SvxFieldItem>( EE_FEATURE_FIELD );
        if(pItem)
        {
            const SvxURLField* pURL = dynamic_cast<const SvxURLField*>( pItem->GetField() );
            if(pURL)
            {
                aLink = pURL->GetURL();
                aTarget = pURL->GetTargetFrame();
            }
        }
    }

    bool bTemp;
    OUString aTemp;

    if ( pSet->GetItemState( EE_CHAR_WEIGHT ) == SfxItemState::SET )
    {
        bTemp = pSet->Get( EE_CHAR_WEIGHT ).GetWeight() == WEIGHT_BOLD;
        aTemp = pState->SetWeight( bTemp );
        if( bTemp )
            aStr.insert(0, aTemp);
        else
            aStr.append(aTemp);
    }

    if ( pSet->GetItemState( EE_CHAR_UNDERLINE ) == SfxItemState::SET )
    {
        bTemp = pSet->Get( EE_CHAR_UNDERLINE ).GetLineStyle() != LINESTYLE_NONE;
        aTemp = pState->SetUnderline( bTemp );
        if( bTemp )
            aStr.insert(0, aTemp);
        else
            aStr.append(aTemp);
    }

    if ( pSet->GetItemState( EE_CHAR_STRIKEOUT ) == SfxItemState::SET )
    {
        bTemp = pSet->Get( EE_CHAR_STRIKEOUT ).GetStrikeout() != STRIKEOUT_NONE;
        aTemp = pState->SetStrikeout( bTemp );
        if( bTemp )
            aStr.insert(0, aTemp);
        else
            aStr.append(aTemp);
    }

    if ( pSet->GetItemState( EE_CHAR_ITALIC ) == SfxItemState::SET )
    {
        bTemp = pSet->Get( EE_CHAR_ITALIC ).GetPosture() != ITALIC_NONE;
        aTemp = pState->SetItalic( bTemp );
        if( bTemp )
            aStr.insert(0, aTemp);
        else
            aStr.append(aTemp);
    }

    if (!aLink.isEmpty())
        aStr.insert(0, pState->SetLink(aLink, aTarget));
    else
        aStr.append(pState->SetLink(aLink, aTarget));

    return aStr.makeStringAndClear();
}

// escapes a string for html
OUString StringToHTMLString( const OUString& rString )
{
    SvMemoryStream aMemStm;
    HTMLOutFuncs::Out_String( aMemStm, rString );
    aMemStm.WriteChar( char(0) );
    sal_Int32 nLength = strlen(static_cast<char const *>(aMemStm.GetData()));
    return OUString( static_cast<char const *>(aMemStm.GetData()), nLength, RTL_TEXTENCODING_UTF8 );
}

// converts a paragraph of the outliner to html
OUString ParagraphToHTMLString( SdrOutliner const * pOutliner, sal_Int32 nPara )
{
    OUStringBuffer aStr;

    if(nullptr == pOutliner)
        return OUString();

    // TODO: MALTE!!!
    EditEngine& rEditEngine = *const_cast<EditEngine*>(&pOutliner->GetEditEngine());
    bool bOldUpdateMode = rEditEngine.SetUpdateLayout(true);

    Paragraph* pPara = pOutliner->GetParagraph(nPara);
    if(nullptr == pPara)
        return OUString();

    HtmlState aState( COL_BLACK );
    std::vector<sal_Int32> aPortionList;
    rEditEngine.GetPortions( nPara, aPortionList );

    sal_Int32 nPos1 = 0;
    for( sal_Int32 nPos2 : aPortionList )
    {
        ESelection aSelection( nPara, nPos1, nPara, nPos2);

        SfxItemSet aSet( rEditEngine.GetAttribs( aSelection ) );

        aStr.append(TextAttribToHTMLString( &aSet, &aState ) +
            StringToHTMLString(rEditEngine.GetText( aSelection )));

        nPos1 = nPos2;
    }
    aStr.append(aState.Flush());
    rEditEngine.SetUpdateLayout(bOldUpdateMode);

    return aStr.makeStringAndClear();
}

void WriteOutlinerParagraph(OUStringBuffer& aStr, SdrOutliner* pOutliner,
                                        OutlinerParaObject const * pOutlinerParagraphObject,
                                        bool bHeadLine)
{
    if (pOutlinerParagraphObject == nullptr)
        return;

    pOutliner->SetText(*pOutlinerParagraphObject);

    sal_Int32 nCount = pOutliner->GetParagraphCount();


    sal_Int16 nCurrentDepth = -1;

    for (sal_Int32 nIndex = 0; nIndex < nCount; nIndex++)
    {
        Paragraph* pParagraph = pOutliner->GetParagraph(nIndex);
        if(pParagraph == nullptr)
            continue;

        const sal_Int16 nDepth = static_cast<sal_uInt16>(pOutliner->GetDepth(nIndex));
        OUString aParaText = ParagraphToHTMLString(pOutliner, nIndex);

        if (aParaText.isEmpty())
            continue;

        if (nDepth < 0)
        {
            OUString aTag = bHeadLine ? OUString("h2") : OUString("p");
            lclAppendStyle(aStr, aTag, getParagraphStyle(pOutliner, nIndex));

            aStr.append(aParaText);
            aStr.append("</" + aTag + ">\r\n");
        }
        else
        {
            while(nCurrentDepth < nDepth)
            {
                aStr.append("<ul>\r\n");
                nCurrentDepth++;
            }
            while(nCurrentDepth > nDepth)
            {
                aStr.append("</ul>\r\n");
                nCurrentDepth--;
            }
            lclAppendStyle(aStr, u"li", getParagraphStyle(pOutliner, nIndex));
            aStr.append(aParaText);
            aStr.append("</li>\r\n");
        }
    }
    while(nCurrentDepth >= 0)
    {
        aStr.append("</ul>\r\n");
        nCurrentDepth--;
    }
    pOutliner->Clear();
}

void WriteTable(OUStringBuffer& aStr, SdrTableObj const * pTableObject, SdrOutliner* pOutliner)
{
    CellPos aStart, aEnd;

    aStart = SdrTableObj::getFirstCell();
    aEnd = pTableObject->getLastCell();

    sal_Int32 nColCount = pTableObject->getColumnCount();
    aStr.append("<table>\r\n");
    for (sal_Int32 nRow = aStart.mnRow; nRow <= aEnd.mnRow; nRow++)
    {
        aStr.append("  <tr>\r\n");
        for (sal_Int32 nCol = aStart.mnCol; nCol <= aEnd.mnCol; nCol++)
        {
            aStr.append("    <td>\r\n");
            sal_Int32 nCellIndex = nRow * nColCount + nCol;
            SdrText* pText = pTableObject->getText(nCellIndex);

            if (pText == nullptr)
                continue;
            WriteOutlinerParagraph(aStr, pOutliner, pText->GetOutlinerParaObject(), false);
            aStr.append("    </td>\r\n");
        }
        aStr.append("  </tr>\r\n");
    }
    aStr.append("</table>\r\n");
}

void WriteObjectGroup(OUStringBuffer& aStr, SdrObjGroup const * pObjectGroup, SdrOutliner* pOutliner,
                                  bool bHeadLine)
{
    SdrObjListIter aGroupIterator(pObjectGroup->GetSubList(), SdrIterMode::DeepNoGroups);
    while (aGroupIterator.IsMore())
    {
        SdrObject* pCurrentObject = aGroupIterator.Next();
        if (pCurrentObject->GetObjIdentifier() == SdrObjKind::Group)
        {
            SdrObjGroup* pCurrentGroupObject = static_cast<SdrObjGroup*>(pCurrentObject);
            WriteObjectGroup(aStr, pCurrentGroupObject, pOutliner, bHeadLine);
        }
        else
        {
            OutlinerParaObject* pOutlinerParagraphObject = pCurrentObject->GetOutlinerParaObject();
            if (pOutlinerParagraphObject != nullptr)
            {
                WriteOutlinerParagraph(aStr, pOutliner, pOutlinerParagraphObject, bHeadLine);
            }
        }
    }
}

// get SdrTextObject with layout text of this page
SdrTextObj* GetLayoutTextObject(SdrPage const * pPage)
{
    SdrTextObj*     pResult      = nullptr;

    for (const rtl::Reference<SdrObject>& pObject : *pPage)
    {
        if (pObject->GetObjInventor() == SdrInventor::Default &&
            pObject->GetObjIdentifier() == SdrObjKind::OutlineText)
        {
            pResult = static_cast<SdrTextObj*>(pObject.get());
            break;
        }
    }
    return pResult;
}


/** creates an outliner text for the title objects of a page
 */
OUString CreateTextForTitle( SdrOutliner* pOutliner, SdPage* pPage )
{
    SdrTextObj* pTO = static_cast<SdrTextObj*>(pPage->GetPresObj(PresObjKind::Title));
    if(!pTO)
        pTO = GetLayoutTextObject(pPage);

    if (pTO && !pTO->IsEmptyPresObj())
    {
        OutlinerParaObject* pOPO = pTO->GetOutlinerParaObject();
        if(pOPO && pOutliner->GetParagraphCount() != 0)
        {
            pOutliner->Clear();
            pOutliner->SetText(*pOPO);
            return ParagraphToHTMLString(pOutliner, 0);
        }
    }

    return OUString();
}

// creates an outliner text for a page
OUString CreateTextForPage(SdrOutliner* pOutliner, SdPage const * pPage,
                                       bool bHeadLine)
{
    OUStringBuffer aStr;

    for (const rtl::Reference<SdrObject>& pObject : *pPage)
    {
        PresObjKind eKind = pPage->GetPresObjKind(pObject.get());

        switch (eKind)
        {
            case PresObjKind::NONE:
            {
                if (pObject->GetObjIdentifier() == SdrObjKind::Group)
                {
                    SdrObjGroup* pObjectGroup = static_cast<SdrObjGroup*>(pObject.get());
                    WriteObjectGroup(aStr, pObjectGroup, pOutliner, false);
                }
                else if (pObject->GetObjIdentifier() == SdrObjKind::Table)
                {
                    SdrTableObj* pTableObject = static_cast<SdrTableObj*>(pObject.get());
                    WriteTable(aStr, pTableObject, pOutliner);
                }
                else
                {
                    if (pObject->GetOutlinerParaObject())
                    {
                        WriteOutlinerParagraph(aStr, pOutliner, pObject->GetOutlinerParaObject(), false);
                    }
                }
            }
            break;

            case PresObjKind::Table:
            {
                SdrTableObj* pTableObject = static_cast<SdrTableObj*>(pObject.get());
                WriteTable(aStr, pTableObject, pOutliner);
            }
            break;

            case PresObjKind::Text:
            case PresObjKind::Outline:
            {
                SdrTextObj* pTextObject = static_cast<SdrTextObj*>(pObject.get());
                if (pTextObject->IsEmptyPresObj())
                    continue;
                WriteOutlinerParagraph(aStr, pOutliner, pTextObject->GetOutlinerParaObject(), bHeadLine);
            }
            break;

            default:
                break;
        }
    }
    return aStr.makeStringAndClear();
}

} // namespace

constexpr OUStringLiteral gaHTMLHeader(
            u"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\r\n"
            "     \"http://www.w3.org/TR/html4/transitional.dtd\">\r\n"
            "<html>\r\n<head>\r\n" );

constexpr OUStringLiteral gaHTMLExtension = u"" STR_HTMLEXP_DEFAULT_EXTENSION;

// constructor for the html export helper classes
HtmlExport::HtmlExport(
    OUString aPath,
    SdDrawDocument* pExpDoc,
    sd::DrawDocShell* pDocShell )
    :   maPath(std::move( aPath )),
        mpDoc(pExpDoc),
        mpDocSh( pDocShell )
{
    bool bChange = mpDoc->IsChanged();

    Init();

    ExportSingleDocument();

    mpDoc->SetChanged(bChange);
}

HtmlExport::~HtmlExport()
{
}

void HtmlExport::Init()
{
    SdPage* pPage = mpDoc->GetSdPage(0, PageKind::Standard);

    // we come up with a destination...
    INetURLObject aINetURLObj( maPath );
    DBG_ASSERT( aINetURLObj.GetProtocol() != INetProtocol::NotValid, "invalid URL" );

    maExportPath = aINetURLObj.GetPartBeforeLastName(); // with trailing '/'
    maIndex = aINetURLObj.GetLastName();

    mnSdPageCount = mpDoc->GetSdPageCount( PageKind::Standard );
    for( sal_uInt16 nPage = 0; nPage < mnSdPageCount; nPage++ )
    {
        pPage = mpDoc->GetSdPage( nPage, PageKind::Standard );

        maPages.push_back( pPage );
    }
    mnSdPageCount = maPages.size();

    maDocFileName = maIndex;
}

void HtmlExport::ExportSingleDocument()
{
    SdrOutliner* pOutliner = mpDoc->GetInternalOutliner();

    mnPagesWritten = 0;
    InitProgress(mnSdPageCount);

    OUStringBuffer aStr(gaHTMLHeader
        + DocumentMetadata()
        + "\r\n"
        "</head>\r\n"
        "<body>\r\n");

    for(sal_uInt16 nSdPage = 0; nSdPage < mnSdPageCount; ++nSdPage)
    {
        SdPage* pPage = maPages[nSdPage];

        // page title
        OUString sTitleText(CreateTextForTitle(pOutliner, pPage));
        OUString sStyle;

        if (nSdPage != 0) // First page - no need for a page break here
            sStyle += "page-break-before:always; ";
        sStyle += getParagraphStyle(pOutliner, 0);

        lclAppendStyle(aStr, u"h1", sStyle);

        aStr.append(sTitleText + "</h1>\r\n");

        // write outline text
        aStr.append(CreateTextForPage( pOutliner, pPage, true));

        if (mpProgress)
            mpProgress->SetState(++mnPagesWritten);

    }

    // close page
    aStr.append("</body>\r\n</html>");

    WriteHtml(maDocFileName, false, aStr);

    pOutliner->Clear();
    ResetProgress();
}

void HtmlExport::InitProgress( sal_uInt16 nProgrCount )
{
    mpProgress.reset(new SfxProgress( mpDocSh, SdResId(STR_CREATE_PAGES), nProgrCount ));
}

void HtmlExport::ResetProgress()
{
    mpProgress.reset();
}

OUString HtmlExport::DocumentMetadata() const
{
    SvMemoryStream aStream;

    uno::Reference<document::XDocumentProperties> xDocProps;
    if (mpDocSh)
    {
        uno::Reference<document::XDocumentPropertiesSupplier> xDPS(
            mpDocSh->GetModel(), uno::UNO_QUERY_THROW);
        xDocProps.set(xDPS->getDocumentProperties());
    }

    SfxFrameHTMLWriter::Out_DocInfo(aStream, maDocFileName, xDocProps,
            "  ");

    const sal_uInt64 nLen = aStream.GetSize();
    OSL_ENSURE(nLen < o3tl::make_unsigned(SAL_MAX_INT32), "Stream can't fit in OString");
    std::string_view aData(static_cast<const char*>(aStream.GetData()), static_cast<sal_Int32>(nLen));

    return OStringToOUString(aData, RTL_TEXTENCODING_UTF8);
}

/** exports the given html data into a non unicode file in the current export path with
    the given filename */
bool HtmlExport::WriteHtml( const OUString& rFileName, bool bAddExtension, std::u16string_view rHtmlData )
{
    ErrCode nErr = ERRCODE_NONE;

    OUString aFileName( rFileName );
    if( bAddExtension )
        aFileName += gaHTMLExtension;

    EasyFile aFile;
    SvStream* pStr;
    OUString aFull(maExportPath + aFileName);
    nErr = aFile.createStream(aFull , pStr);
    if(nErr == ERRCODE_NONE)
    {
        OString aStr(OUStringToOString(rHtmlData, RTL_TEXTENCODING_UTF8));
        pStr->WriteOString( aStr );
        aFile.close();
    }

    if( nErr != ERRCODE_NONE )
        ErrorHandler::HandleError(nErr);

    return nErr == ERRCODE_NONE;
}

EasyFile::EasyFile() : bOpen(false)
{
}

EasyFile::~EasyFile()
{
    if( bOpen )
        close();
}

ErrCode EasyFile::createStream(  const OUString& rUrl, SvStream* &rpStr )
{
    if(bOpen)
        close();

    OUString aFileName;
    createFileName( rUrl, aFileName );

    ErrCode nErr = ERRCODE_NONE;
    pOStm = ::utl::UcbStreamHelper::CreateStream( aFileName, StreamMode::WRITE | StreamMode::TRUNC );
    if( pOStm )
    {
        bOpen = true;
        nErr = pOStm->GetError();
    }
    else
    {
        nErr = ERRCODE_SFX_CANTCREATECONTENT;
    }

    if( nErr != ERRCODE_NONE )
    {
        bOpen = false;
        pOStm.reset();
    }

    rpStr = pOStm.get();

    return nErr;
}

void EasyFile::createFileName(  const OUString& rURL, OUString& rFileName )
{
    if( bOpen )
        close();

    INetURLObject aURL( rURL );

    if( aURL.GetProtocol() == INetProtocol::NotValid )
    {
        OUString aURLStr;
        osl::FileBase::getFileURLFromSystemPath( rURL, aURLStr );
        aURL = INetURLObject( aURLStr );
    }
    DBG_ASSERT( aURL.GetProtocol() != INetProtocol::NotValid, "invalid URL" );
    rFileName = aURL.GetMainURL( INetURLObject::DecodeMechanism::NONE );
}

void EasyFile::close()
{
    pOStm.reset();
    bOpen = false;
}

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