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

using namespace ::sw::mark;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;

namespace sw { namespace mark
{

    SwPosition FindFieldSep(IFieldmark const& rMark)
    {
        SwPosition const& rStartPos(rMark.GetMarkStart());
        SwPosition const& rEndPos(rMark.GetMarkEnd());
        SwNodes const& rNodes(rStartPos.nNode.GetNodes());
        sal_uLong const nStartNode(rStartPos.nNode.GetIndex());
        sal_uLong const nEndNode(rEndPos.nNode.GetIndex());
        int nFields(0);
        boost::optional<SwPosition> ret;
        for (sal_uLong n = nEndNode; nStartNode <= n; --n)
        {
            SwNode *const pNode(rNodes[n]);
            if (pNode->IsTextNode())
            {
                SwTextNode & rTextNode(*pNode->GetTextNode());
                sal_Int32 const nStart(n == nStartNode
                        ? rStartPos.nContent.GetIndex() + 1
                        : 0);
                sal_Int32 const nEnd(n == nEndNode
                        // subtract 1 to ignore the end char
                        ? rEndPos.nContent.GetIndex() - 1
                        : rTextNode.Len());
                for (sal_Int32 i = nEnd; nStart < i; --i)
                {
                    const sal_Unicode c(rTextNode.GetText()[i - 1]);
                    switch (c)
                    {
                        case CH_TXT_ATR_FIELDSTART:
                            --nFields;
                            assert(0 <= nFields);
                            break;
                        case CH_TXT_ATR_FIELDEND:
                            ++nFields;
                            // fields in field result could happen by manual
                            // editing, although the field update deletes them
                            break;
                        case CH_TXT_ATR_FIELDSEP:
                            if (nFields == 0)
                            {
                                assert(!ret); // one per field
                                ret = SwPosition(rTextNode, i - 1);
#ifndef DBG_UTIL
                                return *ret;
#endif
                            }
                            break;
                    }
                }
            }
            else if (pNode->IsEndNode())
            {
                assert(nStartNode <= pNode->StartOfSectionIndex());
                // fieldmark cannot overlap node section
                n = pNode->StartOfSectionIndex();
            }
            else
            {
                assert(pNode->IsNoTextNode());
            }
        }
        assert(ret); // must have found it
        return *ret;
    }
} } // namespace sw::mark

namespace
{
    void lcl_FixPosition(SwPosition& rPos)
    {
        // make sure the position has 1) the proper node, and 2) a proper index
        SwTextNode* pTextNode = rPos.nNode.GetNode().GetTextNode();
        if(pTextNode == nullptr && rPos.nContent.GetIndex() > 0)
        {
            SAL_INFO(
                "sw.core",
                "illegal position: " << rPos.nContent.GetIndex()
                    << " without proper TextNode");
            rPos.nContent.Assign(nullptr, 0);
        }
        else if(pTextNode != nullptr && rPos.nContent.GetIndex() > pTextNode->Len())
        {
            SAL_INFO(
                "sw.core",
                "illegal position: " << rPos.nContent.GetIndex()
                    << " is beyond " << pTextNode->Len());
            rPos.nContent.Assign(pTextNode, pTextNode->Len());
        }
    }

    void lcl_AssertFieldMarksSet(Fieldmark const * const pField,
        const sal_Unicode aStartMark,
        const sal_Unicode aEndMark)
    {
        if (aEndMark != CH_TXT_ATR_FORMELEMENT)
        {
            SwPosition const& rStart(pField->GetMarkStart());
            assert(rStart.nNode.GetNode().GetTextNode()->GetText()[rStart.nContent.GetIndex()] == aStartMark); (void) rStart; (void) aStartMark;
            SwPosition const sepPos(sw::mark::FindFieldSep(*pField));
            assert(sepPos.nNode.GetNode().GetTextNode()->GetText()[sepPos.nContent.GetIndex()] == CH_TXT_ATR_FIELDSEP); (void) sepPos;
        }
        SwPosition const& rEnd(pField->GetMarkEnd());
        assert(rEnd.nNode.GetNode().GetTextNode()->GetText()[rEnd.nContent.GetIndex() - 1] == aEndMark); (void) rEnd;
    }

    void lcl_SetFieldMarks(Fieldmark* const pField,
        SwDoc* const io_pDoc,
        const sal_Unicode aStartMark,
        const sal_Unicode aEndMark)
    {
        io_pDoc->GetIDocumentUndoRedo().StartUndo(SwUndoId::UI_REPLACE, nullptr);

        SwPosition start = pField->GetMarkStart();
        if (aEndMark != CH_TXT_ATR_FORMELEMENT)
        {
            SwPaM aStartPaM(start);
            io_pDoc->getIDocumentContentOperations().InsertString(aStartPaM, OUString(aStartMark));
            --start.nContent; // restore, it was moved by InsertString
            // do not manipulate via reference directly but call SetMarkStartPos
            // which works even if start and end pos were the same
            pField->SetMarkStartPos( start );
            SwPosition& rEnd = pField->GetMarkEnd(); // note: retrieve after
            // setting start, because if start==end it can go stale, see SetMarkPos()
            *aStartPaM.GetPoint() = rEnd;
            io_pDoc->getIDocumentContentOperations().InsertString(aStartPaM, OUString(CH_TXT_ATR_FIELDSEP));
            ++rEnd.nContent;
        }

        SwPosition& rEnd = pField->GetMarkEnd();
        if (aEndMark)
        {
            SwPaM aEndPaM(rEnd);
            io_pDoc->getIDocumentContentOperations().InsertString(aEndPaM, OUString(aEndMark));
            ++rEnd.nContent;
        }
        lcl_AssertFieldMarksSet(pField, aStartMark, aEndMark);

        io_pDoc->GetIDocumentUndoRedo().EndUndo(SwUndoId::UI_REPLACE, nullptr);
    };

    void lcl_RemoveFieldMarks(Fieldmark const * const pField,
        SwDoc* const io_pDoc,
        const sal_Unicode aStartMark,
        const sal_Unicode aEndMark)
    {
        io_pDoc->GetIDocumentUndoRedo().StartUndo(SwUndoId::UI_REPLACE, nullptr);

        const SwPosition& rStart = pField->GetMarkStart();
        SwTextNode const*const pStartTextNode = rStart.nNode.GetNode().GetTextNode();
        assert(pStartTextNode);
        if (aEndMark != CH_TXT_ATR_FORMELEMENT)
        {
            (void) pStartTextNode;
            // check this before start / end because of the +1 / -1 ...
            SwPosition const sepPos(sw::mark::FindFieldSep(*pField));
            io_pDoc->GetDocumentContentOperationsManager().DeleteDummyChar(rStart, aStartMark);
            io_pDoc->GetDocumentContentOperationsManager().DeleteDummyChar(sepPos, CH_TXT_ATR_FIELDSEP);
        }

        const SwPosition& rEnd = pField->GetMarkEnd();
        SwTextNode *const pEndTextNode = rEnd.nNode.GetNode().GetTextNode();
        assert(pEndTextNode);
        const sal_Int32 nEndPos = (rEnd == rStart)
                                   ? rEnd.nContent.GetIndex()
                                   : rEnd.nContent.GetIndex() - 1;
        assert(pEndTextNode->GetText()[nEndPos] == aEndMark);
        SwPosition const aEnd(*pEndTextNode, nEndPos);
        io_pDoc->GetDocumentContentOperationsManager().DeleteDummyChar(aEnd, aEndMark);

        io_pDoc->GetIDocumentUndoRedo().EndUndo(SwUndoId::UI_REPLACE, nullptr);
    };
}

namespace sw { namespace mark
{
    MarkBase::MarkBase(const SwPaM& aPaM,
        const OUString& rName)
        : m_pPos1(new SwPosition(*(aPaM.GetPoint())))
        , m_aName(rName)
    {
        m_pPos1->nContent.SetMark(this);
        lcl_FixPosition(*m_pPos1);
        if (aPaM.HasMark() && (*aPaM.GetMark() != *aPaM.GetPoint()))
        {
            MarkBase::SetOtherMarkPos(*(aPaM.GetMark()));
            lcl_FixPosition(*m_pPos2);
        }
    }

    // For fieldmarks, the CH_TXT_ATR_FIELDSTART and CH_TXT_ATR_FIELDEND
    // themselves are part of the covered range. This is guaranteed by
    // TextFieldmark::InitDoc/lcl_AssureFieldMarksSet.
    bool MarkBase::IsCoveringPosition(const SwPosition& rPos) const
    {
        return GetMarkStart() <= rPos && rPos < GetMarkEnd();
    }

    void MarkBase::SetMarkPos(const SwPosition& rNewPos)
    {
        std::make_unique<SwPosition>(rNewPos).swap(m_pPos1);
        m_pPos1->nContent.SetMark(this);
    }

    void MarkBase::SetOtherMarkPos(const SwPosition& rNewPos)
    {
        std::make_unique<SwPosition>(rNewPos).swap(m_pPos2);
        m_pPos2->nContent.SetMark(this);
    }

    OUString MarkBase::ToString( ) const
    {
        return "Mark: ( Name, [ Node1, Index1 ] ): ( " + m_aName + ", [ "
            + OUString::number( GetMarkPos().nNode.GetIndex( ) )  + ", "
            + OUString::number( GetMarkPos().nContent.GetIndex( ) ) + " ] )";
    }

    void MarkBase::dumpAsXml(xmlTextWriterPtr pWriter) const
    {
        xmlTextWriterStartElement(pWriter, BAD_CAST("MarkBase"));
        xmlTextWriterWriteAttribute(pWriter, BAD_CAST("name"), BAD_CAST(m_aName.toUtf8().getStr()));
        xmlTextWriterStartElement(pWriter, BAD_CAST("markPos"));
        GetMarkPos().dumpAsXml(pWriter);
        xmlTextWriterEndElement(pWriter);
        if (IsExpanded())
        {
            xmlTextWriterStartElement(pWriter, BAD_CAST("otherMarkPos"));
            GetOtherMarkPos().dumpAsXml(pWriter);
            xmlTextWriterEndElement(pWriter);
        }
        xmlTextWriterEndElement(pWriter);
    }

    MarkBase::~MarkBase()
    { }

    OUString MarkBase::GenerateNewName(const OUString& rPrefix)
    {
        static bool bHack = (getenv("LIBO_ONEWAY_STABLE_ODF_EXPORT") != nullptr);

        if (bHack)
        {
            static sal_Int64 nIdCounter = SAL_CONST_INT64(6000000000);
            return rPrefix + OUString::number(nIdCounter++);
        }
        else
        {
            static OUString sUniquePostfix;
            static sal_Int32 nCount = SAL_MAX_INT32;
            if(nCount == SAL_MAX_INT32)
            {
                unsigned int const n(comphelper::rng::uniform_uint_distribution(0,
                                    std::numeric_limits<unsigned int>::max()));
                sUniquePostfix = "_" + OUString::number(n);
                nCount = 0;
            }
            // putting the counter in front of the random parts will speed up string comparisons
            return rPrefix + OUString::number(nCount++) + sUniquePostfix;
        }
    }

    void MarkBase::Modify( const SfxPoolItem *pOld, const SfxPoolItem *pNew )
    {
        NotifyClients(pOld, pNew);
        if (pOld && (RES_REMOVE_UNO_OBJECT == pOld->Which()))
        {   // invalidate cached uno object
            SetXBookmark(uno::Reference<text::XTextContent>(nullptr));
        }
    }

    // TODO: everything else uses MarkBase::GenerateNewName ?
    NavigatorReminder::NavigatorReminder(const SwPaM& rPaM)
        : MarkBase(rPaM, "__NavigatorReminder__")
    { }

    UnoMark::UnoMark(const SwPaM& aPaM)
        : MarkBase(aPaM, MarkBase::GenerateNewName("__UnoMark__"))
    { }

    DdeBookmark::DdeBookmark(const SwPaM& aPaM)
        : MarkBase(aPaM, MarkBase::GenerateNewName("__DdeLink__"))
    { }

    void DdeBookmark::SetRefObject(SwServerObject* pObj)
    {
        m_aRefObj = pObj;
    }

    void DdeBookmark::DeregisterFromDoc(SwDoc* const pDoc)
    {
        if(m_aRefObj.is())
            pDoc->getIDocumentLinksAdministration().GetLinkManager().RemoveServer(m_aRefObj.get());
    }

    DdeBookmark::~DdeBookmark()
    {
        if( m_aRefObj.is() )
        {
            if(m_aRefObj->HasDataLinks())
            {
                ::sfx2::SvLinkSource* p = m_aRefObj.get();
                p->SendDataChanged();
            }
            m_aRefObj->SetNoServer();
        }
    }

    Bookmark::Bookmark(const SwPaM& aPaM,
        const vcl::KeyCode& rCode,
        const OUString& rName)
        : DdeBookmark(aPaM)
        , ::sfx2::Metadatable()
        , m_aCode(rCode)
        , m_bHidden(false)
    {
        m_aName = rName;
    }

    void Bookmark::InitDoc(SwDoc* const io_pDoc, sw::mark::InsertMode const)
    {
        if (io_pDoc->GetIDocumentUndoRedo().DoesUndo())
        {
            io_pDoc->GetIDocumentUndoRedo().AppendUndo(
                    std::make_unique<SwUndoInsBookmark>(*this));
        }
        io_pDoc->getIDocumentState().SetModified();
    }

    void Bookmark::DeregisterFromDoc(SwDoc* const io_pDoc)
    {
        DdeBookmark::DeregisterFromDoc(io_pDoc);

        if (io_pDoc->GetIDocumentUndoRedo().DoesUndo())
        {
            io_pDoc->GetIDocumentUndoRedo().AppendUndo(
                    std::make_unique<SwUndoDeleteBookmark>(*this));
        }
        io_pDoc->getIDocumentState().SetModified();
    }

    ::sfx2::IXmlIdRegistry& Bookmark::GetRegistry()
    {
        SwDoc *const pDoc( GetMarkPos().GetDoc() );
        assert(pDoc);
        return pDoc->GetXmlIdRegistry();
    }

    bool Bookmark::IsInClipboard() const
    {
        SwDoc *const pDoc( GetMarkPos().GetDoc() );
        assert(pDoc);
        return pDoc->IsClipBoard();
    }

    bool Bookmark::IsInUndo() const
    {
        return false;
    }

    bool Bookmark::IsInContent() const
    {
        SwDoc *const pDoc( GetMarkPos().GetDoc() );
        assert(pDoc);
        return !pDoc->IsInHeaderFooter( GetMarkPos().nNode );
    }

    uno::Reference< rdf::XMetadatable > Bookmark::MakeUnoObject()
    {
        SwDoc *const pDoc( GetMarkPos().GetDoc() );
        assert(pDoc);
        const uno::Reference< rdf::XMetadatable> xMeta(
                SwXBookmark::CreateXBookmark(*pDoc, this), uno::UNO_QUERY);
        return xMeta;
    }

    Fieldmark::Fieldmark(const SwPaM& rPaM)
        : MarkBase(rPaM, MarkBase::GenerateNewName("__Fieldmark__"))
    {
        if(!IsExpanded())
            SetOtherMarkPos(GetMarkPos());
    }

    void Fieldmark::SetMarkStartPos( const SwPosition& rNewStartPos )
    {
        if ( GetMarkPos( ) <= GetOtherMarkPos( ) )
            return SetMarkPos( rNewStartPos );
        else
            return SetOtherMarkPos( rNewStartPos );
    }

    void Fieldmark::SetMarkEndPos( const SwPosition& rNewEndPos )
    {
        if ( GetMarkPos( ) <= GetOtherMarkPos( ) )
            return SetOtherMarkPos( rNewEndPos );
        else
            return SetMarkPos( rNewEndPos );
    }

    OUString Fieldmark::ToString( ) const
    {
        return "Fieldmark: ( Name, Type, [ Nd1, Id1 ], [ Nd2, Id2 ] ): ( " + m_aName + ", "
            + m_aFieldname + ", [ " + OUString::number( GetMarkPos().nNode.GetIndex( ) )
            + ", " + OUString::number( GetMarkPos( ).nContent.GetIndex( ) ) + " ], ["
            + OUString::number( GetOtherMarkPos().nNode.GetIndex( ) ) + ", "
            + OUString::number( GetOtherMarkPos( ).nContent.GetIndex( ) ) + " ] ) ";
    }

    void Fieldmark::Invalidate( )
    {
        // TODO: Does exist a better solution to trigger a format of the
        //       fieldmark portion? If yes, please use it.
        SwPaM aPaM( GetMarkPos(), GetOtherMarkPos() );
        aPaM.InvalidatePaM();
    }

    void Fieldmark::dumpAsXml(xmlTextWriterPtr pWriter) const
    {
        xmlTextWriterStartElement(pWriter, BAD_CAST("Fieldmark"));
        xmlTextWriterWriteAttribute(pWriter, BAD_CAST("fieldname"), BAD_CAST(m_aFieldname.toUtf8().getStr()));
        xmlTextWriterWriteAttribute(pWriter, BAD_CAST("fieldHelptext"), BAD_CAST(m_aFieldHelptext.toUtf8().getStr()));
        MarkBase::dumpAsXml(pWriter);
        xmlTextWriterStartElement(pWriter, BAD_CAST("parameters"));
        for (auto& rParam : m_vParams)
        {
            xmlTextWriterStartElement(pWriter, BAD_CAST("parameter"));
            xmlTextWriterWriteAttribute(pWriter, BAD_CAST("name"), BAD_CAST(rParam.first.toUtf8().getStr()));
            xmlTextWriterWriteAttribute(pWriter, BAD_CAST("value"), BAD_CAST(comphelper::anyToString(rParam.second).toUtf8().getStr()));
            xmlTextWriterEndElement(pWriter);
        }
        xmlTextWriterEndElement(pWriter);
        xmlTextWriterEndElement(pWriter);
    }

    TextFieldmark::TextFieldmark(const SwPaM& rPaM, const OUString& rName)
        : Fieldmark(rPaM)
    {
        if ( !rName.isEmpty() )
            m_aName = rName;
    }

    void TextFieldmark::InitDoc(SwDoc* const io_pDoc, sw::mark::InsertMode const eMode)
    {
        if (eMode == sw::mark::InsertMode::New)
        {
            lcl_SetFieldMarks(this, io_pDoc, CH_TXT_ATR_FIELDSTART, CH_TXT_ATR_FIELDEND);
        }
        else
        {
            lcl_AssertFieldMarksSet(this, CH_TXT_ATR_FIELDSTART, CH_TXT_ATR_FIELDEND);
        }
    }

    void TextFieldmark::ReleaseDoc(SwDoc* const pDoc)
    {
        lcl_RemoveFieldMarks(this, pDoc, CH_TXT_ATR_FIELDSTART, CH_TXT_ATR_FIELDEND);
    }

    NonTextFieldmark::NonTextFieldmark(const SwPaM& rPaM)
        : Fieldmark(rPaM)
    { }

    void NonTextFieldmark::InitDoc(SwDoc* const io_pDoc, sw::mark::InsertMode const eMode)
    {
        if (eMode == sw::mark::InsertMode::New)
        {
            lcl_SetFieldMarks(this, io_pDoc, CH_TXT_ATR_FIELDSTART, CH_TXT_ATR_FORMELEMENT);

            // For some reason the end mark is moved from 1 by the Insert:
            // we don't want this for checkboxes
            SwPosition aNewEndPos = GetMarkEnd();
            aNewEndPos.nContent--;
            SetMarkEndPos( aNewEndPos );
        }
        else
        {
            lcl_AssertFieldMarksSet(this, CH_TXT_ATR_FIELDSTART, CH_TXT_ATR_FORMELEMENT);
        }
    }

    void NonTextFieldmark::ReleaseDoc(SwDoc* const pDoc)
    {
        lcl_RemoveFieldMarks(this, pDoc,
                CH_TXT_ATR_FIELDSTART, CH_TXT_ATR_FORMELEMENT);
    }


    CheckboxFieldmark::CheckboxFieldmark(const SwPaM& rPaM)
        : NonTextFieldmark(rPaM)
    { }

    void CheckboxFieldmark::SetChecked(bool checked)
    {
        if ( IsChecked() != checked )
        {
            (*GetParameters())[OUString(ODF_FORMCHECKBOX_RESULT)] <<= checked;
            // mark document as modified
            SwDoc *const pDoc( GetMarkPos().GetDoc() );
            if ( pDoc )
                pDoc->getIDocumentState().SetModified();
        }
    }

    bool CheckboxFieldmark::IsChecked() const
    {
        bool bResult = false;
        parameter_map_t::const_iterator pResult = GetParameters()->find(OUString(ODF_FORMCHECKBOX_RESULT));
        if(pResult != GetParameters()->end())
            pResult->second >>= bResult;
        return bResult;
    }

    FieldmarkWithDropDownButton::FieldmarkWithDropDownButton(const SwPaM& rPaM)
        : NonTextFieldmark(rPaM)
        , m_pButton(nullptr)
    {
    }

    FieldmarkWithDropDownButton::~FieldmarkWithDropDownButton()
    {
        m_pButton.disposeAndClear();
    }

    void FieldmarkWithDropDownButton::HideButton()
    {
        if(m_pButton)
            m_pButton->Show(false);
    }

    void FieldmarkWithDropDownButton::RemoveButton()
    {
        if(m_pButton)
            m_pButton.disposeAndClear();
    }

    DropDownFieldmark::DropDownFieldmark(const SwPaM& rPaM)
        : FieldmarkWithDropDownButton(rPaM)
    {
    }

    DropDownFieldmark::~DropDownFieldmark()
    {
    }

    void DropDownFieldmark::ShowButton(SwEditWin* pEditWin)
    {
        if(pEditWin)
        {
            if(!m_pButton)
                m_pButton = VclPtr<DropDownFormFieldButton>::Create(pEditWin, *this);
            m_pButton->CalcPosAndSize(m_aPortionPaintArea);
            m_pButton->Show();
        }
    }

    void DropDownFieldmark::SetPortionPaintArea(const SwRect& rPortionPaintArea)
    {
        if(m_aPortionPaintArea == rPortionPaintArea &&
           m_pButton && m_pButton->IsVisible())
            return;

        m_aPortionPaintArea = rPortionPaintArea;
        if(m_pButton)
        {
            m_pButton->Show();
            m_pButton->CalcPosAndSize(m_aPortionPaintArea);
            m_pButton->Invalidate();
        }
    }

    DateFieldmark::DateFieldmark(const SwPaM& rPaM)
        : FieldmarkWithDropDownButton(rPaM)
        , m_pNumberFormatter(nullptr)
        , m_pDocumentContentOperationsManager(nullptr)
    {
    }

    DateFieldmark::~DateFieldmark()
    {
    }

    void DateFieldmark::InitDoc(SwDoc* const io_pDoc, sw::mark::InsertMode eMode)
    {
        m_pNumberFormatter = io_pDoc->GetNumberFormatter();
        m_pDocumentContentOperationsManager = &io_pDoc->GetDocumentContentOperationsManager();
        if (eMode == sw::mark::InsertMode::New)
        {
            lcl_SetFieldMarks(this, io_pDoc, CH_TXT_ATR_FIELDSTART, CH_TXT_ATR_FIELDEND);
        }
        else
        {
            lcl_AssertFieldMarksSet(this, CH_TXT_ATR_FIELDSTART, CH_TXT_ATR_FIELDEND);
        }
    }

    void DateFieldmark::ReleaseDoc(SwDoc* const pDoc)
    {
        lcl_RemoveFieldMarks(this, pDoc, CH_TXT_ATR_FIELDSTART, CH_TXT_ATR_FIELDEND);
    }

    void DateFieldmark::ShowButton(SwEditWin* pEditWin)
    {
        if(pEditWin)
        {
            if(!m_pButton)
                m_pButton = VclPtr<DateFormFieldButton>::Create(pEditWin, *this, m_pNumberFormatter);
            SwRect aPaintArea(m_aPaintAreaStart.TopLeft(), m_aPaintAreaEnd.BottomRight());
            m_pButton->CalcPosAndSize(aPaintArea);
            m_pButton->Show();
        }
    }

    void DateFieldmark::SetPortionPaintAreaStart(const SwRect& rPortionPaintArea)
    {
        if (rPortionPaintArea.IsEmpty())
            return;

        m_aPaintAreaStart = rPortionPaintArea;
        InvalidateCurrentDateParam();
    }

    void DateFieldmark::SetPortionPaintAreaEnd(const SwRect& rPortionPaintArea)
    {
        if (rPortionPaintArea.IsEmpty())
            return;

        if(m_aPaintAreaEnd == rPortionPaintArea &&
           m_pButton && m_pButton->IsVisible())
            return;

        m_aPaintAreaEnd = rPortionPaintArea;
        if(m_pButton)
        {
            m_pButton->Show();
            SwRect aPaintArea(m_aPaintAreaStart.TopLeft(), m_aPaintAreaEnd.BottomRight());
            m_pButton->CalcPosAndSize(aPaintArea);
            m_pButton->Invalidate();
        }
        InvalidateCurrentDateParam();
    }

    OUString DateFieldmark::GetContent() const
    {
        const SwTextNode* const pTextNode = GetMarkEnd().nNode.GetNode().GetTextNode();
        SwPosition const sepPos(sw::mark::FindFieldSep(*this));
#if 0
        const sal_Int32 nStart(sepPos.nContent.GetIndex());
        const sal_Int32 nEnd  (GetMarkEnd().nContent.GetIndex());
#else
        const sal_Int32 nStart(GetMarkStart().nContent.GetIndex());
        const sal_Int32 nEnd  (sepPos.nContent.GetIndex() + 1);
#endif

        OUString sContent;
        if(nStart + 1 < pTextNode->GetText().getLength() && nEnd <= pTextNode->GetText().getLength() &&
           nEnd > nStart + 2)
            sContent = pTextNode->GetText().copy(nStart + 1, nEnd - nStart - 2);
        return sContent;
    }

    void DateFieldmark::ReplaceContent(const OUString& sNewContent)
    {
        if(!m_pDocumentContentOperationsManager)
            return;

        const SwTextNode* const pTextNode = GetMarkEnd().nNode.GetNode().GetTextNode();
        SwPosition const sepPos(sw::mark::FindFieldSep(*this));
#if 0
        const sal_Int32 nStart(sepPos.nContent.GetIndex());
        const sal_Int32 nEnd  (GetMarkEnd().nContent.GetIndex());
#else
        const sal_Int32 nStart(GetMarkStart().nContent.GetIndex());
        const sal_Int32 nEnd  (sepPos.nContent.GetIndex() + 1);
#endif

        if(nStart + 1 < pTextNode->GetText().getLength() && nEnd <= pTextNode->GetText().getLength() &&
           nEnd > nStart + 2)
        {
            SwPaM aFieldPam(GetMarkStart().nNode, nStart + 1,
                            GetMarkStart().nNode, nEnd - 1);
            m_pDocumentContentOperationsManager->ReplaceRange(aFieldPam, sNewContent, false);
        }
        else
        {
            SwPaM aFieldStartPam(GetMarkStart().nNode, nStart + 1);
            m_pDocumentContentOperationsManager->InsertString(aFieldStartPam, sNewContent);
        }

    }

    std::pair<bool, double> DateFieldmark::GetCurrentDate() const
    {
        // Check current date param first
        std::pair<bool, double> aResult = ParseCurrentDateParam();
        if(aResult.first)
            return aResult;

        const sw::mark::IFieldmark::parameter_map_t* pParameters = GetParameters();
        bool bFoundValidDate = false;
        double dCurrentDate = 0;
        OUString sDateFormat;
        auto pResult = pParameters->find(ODF_FORMDATE_DATEFORMAT);
        if (pResult != pParameters->end())
        {
            pResult->second >>= sDateFormat;
        }

        OUString sLang;
        pResult = pParameters->find(ODF_FORMDATE_DATEFORMAT_LANGUAGE);
        if (pResult != pParameters->end())
        {
            pResult->second >>= sLang;
        }

        // Get current content of the field
        OUString sContent = GetContent();

        sal_uInt32 nFormat = m_pNumberFormatter->GetEntryKey(sDateFormat, LanguageTag(sLang).getLanguageType());
        if (nFormat == NUMBERFORMAT_ENTRY_NOT_FOUND)
        {
            sal_Int32 nCheckPos = 0;
            SvNumFormatType nType;
            m_pNumberFormatter->PutEntry(sDateFormat,
                                         nCheckPos,
                                         nType,
                                         nFormat,
                                         LanguageTag(sLang).getLanguageType());
        }

        if (nFormat != NUMBERFORMAT_ENTRY_NOT_FOUND)
        {
            bFoundValidDate = m_pNumberFormatter->IsNumberFormat(sContent, nFormat, dCurrentDate);
        }
        return std::pair<bool, double>(bFoundValidDate, dCurrentDate);
    }

    void DateFieldmark::SetCurrentDate(double fDate)
    {
        // Replace current content with the selected date
        ReplaceContent(GetDateInCurrentDateFormat(fDate));

        // Also save the current date in a standard format
        sw::mark::IFieldmark::parameter_map_t* pParameters = GetParameters();
        (*pParameters)[ODF_FORMDATE_CURRENTDATE] <<= GetDateInStandardDateFormat(fDate);
    }

    OUString DateFieldmark::GetDateInStandardDateFormat(double fDate) const
    {
        OUString sCurrentDate;
        sal_uInt32 nFormat = m_pNumberFormatter->GetEntryKey(ODF_FORMDATE_CURRENTDATE_FORMAT, ODF_FORMDATE_CURRENTDATE_LANGUAGE);
        if (nFormat == NUMBERFORMAT_ENTRY_NOT_FOUND)
        {
            sal_Int32 nCheckPos = 0;
            SvNumFormatType nType;
            OUString sFormat = ODF_FORMDATE_CURRENTDATE_FORMAT;
            m_pNumberFormatter->PutEntry(sFormat,
                                         nCheckPos,
                                         nType,
                                         nFormat,
                                         ODF_FORMDATE_CURRENTDATE_LANGUAGE);
        }

        if (nFormat != NUMBERFORMAT_ENTRY_NOT_FOUND)
        {
            Color* pCol = nullptr;
            m_pNumberFormatter->GetOutputString(fDate, nFormat, sCurrentDate, &pCol, false);
        }
        return sCurrentDate;
    }

    std::pair<bool, double> DateFieldmark::ParseCurrentDateParam() const
    {
        bool bFoundValidDate = false;
        double dCurrentDate = 0;

        const sw::mark::IFieldmark::parameter_map_t* pParameters = GetParameters();
        auto pResult = pParameters->find(ODF_FORMDATE_CURRENTDATE);
        OUString sCurrentDate;
        if (pResult != pParameters->end())
        {
            pResult->second >>= sCurrentDate;
        }
        if(!sCurrentDate.isEmpty())
        {
            sal_uInt32 nFormat = m_pNumberFormatter->GetEntryKey(ODF_FORMDATE_CURRENTDATE_FORMAT, ODF_FORMDATE_CURRENTDATE_LANGUAGE);
            if (nFormat == NUMBERFORMAT_ENTRY_NOT_FOUND)
            {
                sal_Int32 nCheckPos = 0;
                SvNumFormatType nType;
                OUString sFormat = ODF_FORMDATE_CURRENTDATE_FORMAT;
                m_pNumberFormatter->PutEntry(sFormat,
                                             nCheckPos,
                                             nType,
                                             nFormat,
                                             ODF_FORMDATE_CURRENTDATE_LANGUAGE);
            }

            if(nFormat != NUMBERFORMAT_ENTRY_NOT_FOUND)
            {
                bFoundValidDate = m_pNumberFormatter->IsNumberFormat(sCurrentDate, nFormat, dCurrentDate);
            }
        }
        return std::pair<bool, double>(bFoundValidDate, dCurrentDate);
    }


    OUString DateFieldmark::GetDateInCurrentDateFormat(double fDate) const
    {
        // Get current date format and language
        OUString sDateFormat;
        const sw::mark::IFieldmark::parameter_map_t* pParameters = GetParameters();
        auto pResult = pParameters->find(ODF_FORMDATE_DATEFORMAT);
        if (pResult != pParameters->end())
        {
            pResult->second >>= sDateFormat;
        }

        OUString sLang;
        pResult = pParameters->find(ODF_FORMDATE_DATEFORMAT_LANGUAGE);
        if (pResult != pParameters->end())
        {
            pResult->second >>= sLang;
        }

        // Fill the content with the specified format
        OUString sCurrentContent;
        sal_uInt32 nFormat = m_pNumberFormatter->GetEntryKey(sDateFormat, LanguageTag(sLang).getLanguageType());
        if (nFormat == NUMBERFORMAT_ENTRY_NOT_FOUND)
        {
            sal_Int32 nCheckPos = 0;
            SvNumFormatType nType;
            OUString sFormat = sDateFormat;
            m_pNumberFormatter->PutEntry(sFormat,
                                         nCheckPos,
                                         nType,
                                         nFormat,
                                         LanguageTag(sLang).getLanguageType());
        }

        if (nFormat != NUMBERFORMAT_ENTRY_NOT_FOUND)
        {
            Color* pCol = nullptr;
            m_pNumberFormatter->GetOutputString(fDate, nFormat, sCurrentContent, &pCol, false);
        }
        return sCurrentContent;
    }

    void DateFieldmark::InvalidateCurrentDateParam()
    {
        std::pair<bool, double> aResult = ParseCurrentDateParam();
        if(!aResult.first)
            return;

        // Current date became invalid
        if(GetDateInCurrentDateFormat(aResult.second) != GetContent())
        {
            sw::mark::IFieldmark::parameter_map_t* pParameters = GetParameters();
            (*pParameters)[ODF_FORMDATE_CURRENTDATE] <<= OUString();
        }
    }
}}

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