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

#include <string.h>
#include <libxml/xmlwriter.h>

#include <osl/diagnose.h>
#include <sal/log.hxx>
#include <svl/SfxBroadcaster.hxx>
#include <svl/hint.hxx>
#include <svl/itemset.hxx>
#include <tools/debug.hxx>

#include <cassert>
#include <vector>

// WhichIDs that need to set SFX_ITEMINFOFLAG_SUPPORT_SURROGATE in SfxItemInfo
// to true to allow a register of all items of that type/with that WhichID
// to be accessible using SfxItemPool::GetItemSurrogates. Created by
// grepping for 'GetItemSurrogates' usages & interpreting. Some
// are double, more may be necessary. There is a SAL_INFO("svl.items", ...)
// in SfxItemPool::GetItemSurrogates that will give hints on missing flags.
//
// due to SwTable::UpdateFields
// due to SwCursorShell::GotoNxtPrvTableFormula
// due to DocumentFieldsManager::UpdateTableFields
// due to SwTable::GatherFormulas
//  RES_BOXATR_FORMULA ok
// due to SwContentTree::EditEntry
// due to SwDoc::FindINetAttr
// due to SwUndoResetAttr::RedoImpl
// due to SwContentTree::EditEntry
// due to SwContentTree::BringEntryToAttention
//  RES_TXTATR_REFMARK ok
// due to ImpEditEngine::WriteRTF
// due to ScDocument::UpdateFontCharSet()
// due to ScXMLFontAutoStylePool_Impl
// due to SdXImpressDocument::getPropertyValue
// due to Writer::AddFontItems_
//  EE_CHAR_FONTINFO ok
// due to ImpEditEngine::WriteRTF
// due to ScXMLFontAutoStylePool_Impl
// due to SdXImpressDocument::getPropertyValue
// due to Writer::AddFontItems_
//  EE_CHAR_FONTINFO_CJK ok
// due to ImpEditEngine::WriteRTF
// due to ScXMLFontAutoStylePool_Impl
// due to SdXImpressDocument::getPropertyValue
// due to Writer::AddFontItems_
//  EE_CHAR_FONTINFO_CTL ok
// due to ImpEditEngine::WriteRTF
//  EE_CHAR_COLOR ok
// due to ScDocumentPool::StyleDeleted
// due to ScDocument::UpdateFontCharSet()
// due to ScXMLFontAutoStylePool_Impl
//  ATTR_FONT ok
// due to OptimizeHasAttrib
//  ATTR_ROTATE_VALUE ok
// due to ScDocument::GetDocColors()
//  ATTR_BACKGROUND ok
//  ATTR_FONT_COLOR ok
// due to ScXMLExport::CollectUserDefinedNamespaces
//  ATTR_USERDEF ok
// due to ScXMLExport::CollectUserDefinedNamespaces
// due to SwXMLExport::exportDoc
//  EE_PARA_XMLATTRIBS ok
// due to ScXMLExport::CollectUserDefinedNamespaces
// due to SwXMLExport::exportDoc
//  EE_CHAR_XMLATTRIBS ok
// due to ScXMLExport::CollectUserDefinedNamespaces
// due to SwXMLExport::exportDoc
//  SDRATTR_XMLATTRIBUTES ok
// due to ScXMLFontAutoStylePool_Impl
//  ATTR_CJK_FONT ok
//  ATTR_CTL_FONT ok
//  ATTR_PAGE_HEADERLEFT ok
//  ATTR_PAGE_FOOTERLEFT ok
//  ATTR_PAGE_HEADERRIGHT ok
//  ATTR_PAGE_FOOTERRIGHT ok
//  ATTR_PAGE_HEADERFIRST ok
//  ATTR_PAGE_FOOTERFIRST ok
// due to ScCellShell::ExecuteEdit
// due to ScTabViewShell::CreateRefDialogController
//  SCITEM_CONDFORMATDLGDATA ok
// due to SdDrawDocument::UpdatePageRelativeURLs
//  EE_FEATURE_FIELD ok
// due to SvxUnoMarkerTable::replaceByName
// due to SvxShape::setPropertyValueImpl/SvxShape::SetFillAttribute
// due to XLineStartItem::checkForUniqueItem
//  XATTR_LINESTART ok
// due to SvxUnoMarkerTable::replaceByName
// due to SvxShape::setPropertyValueImpl/SvxShape::SetFillAttribute
// due to XLineStartItem::checkForUniqueItem
//  XATTR_LINEEND ok
// due to SvxUnoNameItemTable
// due to SvxShape::setPropertyValueImpl/SvxShape::SetFillAttribute
// due to NameOrIndex::CheckNamedItem all derived from NameOrIndex
//  XATTR_FILLBITMAP ok
// due to SvxUnoNameItemTable
// due to SvxShape::setPropertyValueImpl/SvxShape::SetFillAttribute
//  XATTR_LINEDASH ok
// due to SvxUnoNameItemTable
// due to SvxShape::setPropertyValueImpl/SvxShape::SetFillAttribute
// due to NameOrIndex::CheckNamedItem all derived from NameOrIndex
//  XATTR_FILLGRADIENT ok
// due to SvxUnoNameItemTable
// due to SvxShape::setPropertyValueImpl/SvxShape::SetFillAttribute
//  XATTR_FILLHATCH ok
// due to SvxUnoNameItemTable
// due to SvxShape::setPropertyValueImpl/SvxShape::SetFillAttribute
//  XATTR_FILLFLOATTRANSPARENCE ok
// due to NamespaceIteratorImpl
//      -> needs to be evaluated
// due to SwCursorShell::GotoNxtPrvTOXMark
// due to SwDoc::GetTOIKeys
//  RES_TXTATR_TOXMARK ok
// due to SwDoc::GetRefMark
// due to SwDoc::CallEvent
// due to SwURLStateChanged::Notify
// due to SwHTMLWriter::CollectLinkTargets
// due to MSWordExportBase::CollectOutlineBookmarks
//  RES_TXTATR_INETFMT ok
// due to SwDoc::GetAllUsedDB
// due to lcl_FindInputField
// due to SwViewShell::IsAnyFieldInDoc
//  RES_TXTATR_FIELD ok
// due to SwDoc::GetAllUsedDB
// due to lcl_FindInputField
// due to SwViewShell::IsAnyFieldInDoc
//  RES_TXTATR_INPUTFIELD ok
// due to SwDoc::SetDefault
//  RES_PARATR_TABSTOP ok
// due to SwDoc::GetDocColors()
// due to RtfExport::OutColorTable
//  RES_CHRATR_COLOR ok
// due to SwDoc::GetDocColors()
//  RES_CHRATR_HIGHLIGHT ok
// due to SwDoc::GetDocColors()
//  RES_BACKGROUND ok
// due to SwNode::FindPageDesc
// due to SwPageNumberFieldType::ChangeExpansion
// due to SwFrame::GetVirtPageNum
//  RES_PAGEDESC ok
// due to SwAutoStylesEnumImpl::
//  RES_TXTATR_CJK_RUBY ok
// due to SwHTMLWriter::CollectLinkTargets
// due to MSWordExportBase::CollectOutlineBookmarks
//  RES_URL
// due to RtfExport::OutColorTable
//  RES_CHRATR_UNDERLINE ok
//  RES_CHRATR_OVERLINE ok
//  RES_CHRATR_BACKGROUND ok
//  RES_SHADOW ok
//  RES_BOX ok
//  RES_CHRATR_BOX ok
//  XATTR_FILLCOLOR ok
// due to wwFontHelper::InitFontTable
// due to SwXMLFontAutoStylePool_Impl::SwXMLFontAutoStylePool_Impl
//  RES_CHRATR_FONT ok
// due to wwFontHelper::InitFontTable
// due to SwXMLFontAutoStylePool_Impl::SwXMLFontAutoStylePool_Impl
//  RES_CHRATR_CJK_FONT ok
// due to wwFontHelper::InitFontTable
// due to SwXMLFontAutoStylePool_Impl::SwXMLFontAutoStylePool_Impl
//  RES_CHRATR_CTL_FONT
// due to SwXMLExport::exportDoc
//  RES_UNKNOWNATR_CONTAINER ok
//  RES_TXTATR_UNKNOWN_CONTAINER ok



#if OSL_DEBUG_LEVEL > 0
#include <map>

static void
lcl_CheckSlots2(std::map<sal_uInt16, sal_uInt16> & rSlotMap,
        SfxItemPool const& rPool, SfxItemInfo const* pInfo)
{
    if (!pInfo)
        return; // may not be initialized yet
    if (rPool.GetName() == "EditEngineItemPool")
        return; // HACK: this one has loads of duplicates already, ignore it :(
    sal_uInt16 const nFirst(rPool.GetFirstWhich());
    sal_uInt16 const nCount(rPool.GetLastWhich() - rPool.GetFirstWhich() + 1);
    for (sal_uInt16 n = 0; n < nCount; ++n)
    {
        sal_uInt16 const nSlotId(pInfo[n]._nItemInfoSlotID);
        if (nSlotId != 0
            && nSlotId != 10883  // preexisting duplicate SID_ATTR_GRAF_CROP
            && nSlotId != 10023  // preexisting duplicate SID_ATTR_BORDER_INNER
            && nSlotId != 10024  // preexisting duplicate SID_ATTR_BORDER_OUTER
            && nSlotId != 11013  // preexisting duplicate SID_ATTR_BORDER_DIAG_TLBR
            && nSlotId != 11014) // preexisting duplicate SID_ATTR_BORDER_DIAG_BLTR
        {   // check for duplicate slot-id mapping
            std::map<sal_uInt16, sal_uInt16>::const_iterator const iter(
                rSlotMap.find(nSlotId));
            sal_uInt16 const nWhich(nFirst + n);
            if (iter != rSlotMap.end())
            {
                SAL_WARN("svl", "SfxItemPool: duplicate SlotId " << nSlotId
                        << " mapped to " << iter->second << " and " << nWhich);
                assert(false);
            }
            rSlotMap.insert(std::make_pair(nSlotId, nWhich));
        }
    }
}

#define CHECK_SLOTS() \
do { \
    std::map<sal_uInt16, sal_uInt16> slotmap; \
    for (SfxItemPool * p = mpMaster; p; p = p->mpSecondary.get()) \
    { \
        lcl_CheckSlots2(slotmap, *p, p->pItemInfos); \
    } \
} while (false)

#else
#define CHECK_SLOTS() do {} while (false)
#endif

void SfxItemPool::registerItemSet(SfxItemSet& rSet)
{
    registeredSfxItemSets& rTarget(GetMasterPool()->maRegisteredSfxItemSets);
#ifdef DBG_UTIL
    const size_t nBefore(rTarget.size());
#endif
    rTarget.insert(&rSet);
#ifdef DBG_UTIL
    const size_t nAfter(rTarget.size());
    if (nBefore + 1 != nAfter)
    {
        SAL_WARN("svl.items", "SfxItemPool::registerItemSet: ItemSet was already registered (!)");
    }
#endif
}

void SfxItemPool::unregisterItemSet(SfxItemSet& rSet)
{
    registeredSfxItemSets& rTarget(GetMasterPool()->maRegisteredSfxItemSets);
#ifdef DBG_UTIL
    const size_t nBefore(rTarget.size());
#endif
    rTarget.erase(&rSet);
#ifdef DBG_UTIL
    const size_t nAfter(rTarget.size());
    if (nBefore != nAfter + 1)
    {
        SAL_WARN("svl.items", "SfxItemPool::unregisterItemSet: ItemSet was not registered (!)");
    }
#endif
}

void SfxItemPool::registerPoolItemHolder(SfxPoolItemHolder& rHolder)
{
    registeredSfxPoolItemHolders& rTarget(GetMasterPool()->maRegisteredSfxPoolItemHolders);
#ifdef DBG_UTIL
    const size_t nBefore(rTarget.size());
#endif
    rTarget.insert(&rHolder);
#ifdef DBG_UTIL
    const size_t nAfter(rTarget.size());
    if (nBefore + 1 != nAfter)
    {
        SAL_WARN("svl.items", "SfxItemPool::registerPoolItemHolder: SfxPoolItemHolder was already registered (!)");
    }
#endif
}

void SfxItemPool::unregisterPoolItemHolder(SfxPoolItemHolder& rHolder)
{
    registeredSfxPoolItemHolders& rTarget(GetMasterPool()->maRegisteredSfxPoolItemHolders);
#ifdef DBG_UTIL
    const size_t nBefore(rTarget.size());
#endif
    rTarget.erase(&rHolder);
#ifdef DBG_UTIL
    const size_t nAfter(rTarget.size());
    if (nBefore != nAfter + 1)
    {
        SAL_WARN("svl.items", "SfxItemPool::unregisterPoolItemHolder: SfxPoolItemHolder was not registered (!)");
    }
#endif
}

sal_uInt16 SfxItemPool::GetFirstWhich() const
{
    return mnStart;
}

sal_uInt16 SfxItemPool::GetLastWhich() const
{
    return mnEnd;
}

bool SfxItemPool::IsInRange( sal_uInt16 nWhich ) const
{
    return nWhich >= mnStart && nWhich <= mnEnd;
}

sal_uInt16 SfxItemPool::GetIndex_Impl(sal_uInt16 nWhich) const
{
    if (nWhich < mnStart || nWhich > mnEnd)
    {
        assert(false && "missing bounds check before use");
        return 0;
    }
    return nWhich - mnStart;
}

sal_uInt16 SfxItemPool::GetSize_Impl() const
{
    return mnEnd - mnStart + 1;
}

const SfxPoolItem* SfxItemPool::GetUserDefaultItem( sal_uInt16 nWhich ) const
{
    const SfxPoolItem* pRet;
    if( IsInRange( nWhich ) )
        pRet = maUserDefaults[GetIndex_Impl(nWhich)];
    else if( mpSecondary )
        pRet = mpSecondary->GetUserDefaultItem( nWhich );
    else
    {
        assert(false && "unknown WhichId - cannot get pool default");
        pRet = nullptr;
    }
    return pRet;
}


bool SfxItemPool::CheckItemInfoFlag(sal_uInt16 nWhich, sal_uInt16 nMask) const
{
    if (!IsInRange(nWhich))
    {
        // get to correct pool
        if (mpSecondary)
            return mpSecondary->CheckItemInfoFlag(nWhich, nMask);
        return false;
    }

    return CheckItemInfoFlag_Impl(nWhich - mnStart, nMask);
}

SfxBroadcaster& SfxItemPool::BC()
{
    return aBC;
}


/**
 * This is the regular ctor to be used for this class.
 * An SfxItemPool instance is initialized, which can manage Items in the
 * range from 'nStartWhich' to 'nEndWhich'.
 *
 * For every one of these WhichIds a static Default must be present in the
 * 'pDefaults' array. They start with an SfxPoolItem (with the WhichId
 * 'nStartWhich'), are sorted by WhichId and consecutively stored.
 *
 * 'pItemInfos' is a USHORT array arranged in the same way, which holds
 *  SlotIds and Flags. These SlotIds can be 0, if the affected Items are
 *  exclusively used in the Core.
 *  The flags allow for e.g. enabling value sharing (poolable).
 *
 *  If the Pool is supposed to hold SfxSetItems, the ctor cannot yet contain
 *  static Defaults. This needs to be done afterwards, using
 *  @see SfxItemPool::SetPoolDefaults(std::vector<SfxPoolItem*>*).
 *
 *  @see SfxItemPool::SetPoolDefaults(std::vector<SfxPoolItem*>*)
 *  @see SfxItemPool::ReleasePoolDefaults(std::vector<SfxPoolItem*>*,bool)
 *  @see SfxItemPool::ReleasePoolDefaults(bool)
 */
SfxItemPool::SfxItemPool
(
    const OUString&     rName,          /* Pool name to identify in the file format */
    sal_uInt16          nStartWhich,    /* First WhichId of the Pool (must be > 0) */
    sal_uInt16          nEndWhich,      /* Last WhichId of the Pool */
    const SfxItemInfo*  pInfo,          /* SID Map and Item flags */
    std::vector<SfxPoolItem*>*
                        pDefaults       /* Pointer to static Defaults;
                                           is directly referenced by the Pool,
                                           but no transfer of ownership */
)
: salhelper::SimpleReferenceObject()
,pItemInfos(pInfo)
, aName(rName)
, maUserDefaults(nEndWhich - nStartWhich + 1)
, mpPoolDefaults(nullptr)
, mpMaster(this)
, mnStart(nStartWhich)
, mnEnd(nEndWhich)
, eDefMetric(MapUnit::MapCM)
, maRegisteredSfxItemSets()
, maRegisteredSfxPoolItemHolders()
, mbPreDeleteDone(false)
{
    eDefMetric = MapUnit::MapTwip;

    if ( pDefaults )
        SetPoolDefaults(pDefaults);

#ifdef DBG_UTIL
    if (pItemInfos)
    {
        auto p = pItemInfos;
        auto nWhich = nStartWhich;
        while (nWhich <= nEndWhich)
        {
            if (p->_nItemInfoSlotID == nWhich)
            {
                SAL_WARN("svl.items", "No point mapping a SID to itself, just put a 0 here in the SfxItemInfo array, at index " << (p - pItemInfos));
                assert(false);
            }
            ++p;
            ++nWhich;
        }
    }
#endif
}


/**
 * Copy ctor
 *
 * @see SfxItemPool::Clone() const
*/
SfxItemPool::SfxItemPool
(
    const SfxItemPool&  rPool,                  //  Copy from this instance
    bool                bCloneStaticDefaults    /*  true
                                                    Copy static Defaults

                                                    false
                                                    Take over static Defaults */
)
: salhelper::SimpleReferenceObject()
, pItemInfos(rPool.pItemInfos)
, aName(rPool.aName)
, maUserDefaults(rPool.mnEnd - rPool.mnStart + 1)
, mpPoolDefaults(nullptr)
, mpMaster(this)
, mnStart(rPool.mnStart)
, mnEnd(rPool.mnEnd)
, eDefMetric(MapUnit::MapCM)
, maRegisteredSfxItemSets()
, maRegisteredSfxPoolItemHolders()
, mbPreDeleteDone(false)
{
    eDefMetric = rPool.eDefMetric;

    // Take over static Defaults
    if ( bCloneStaticDefaults )
    {
        std::vector<SfxPoolItem *>* ppDefaults = new std::vector<SfxPoolItem*>(mnEnd-mnStart+1);
        for ( sal_uInt16 n = 0; n <= mnEnd - mnStart; ++n )
        {
            (*ppDefaults)[n] = (*rPool.mpPoolDefaults)[n]->Clone(this);
            (*ppDefaults)[n]->setStaticDefault();
        }

        SetPoolDefaults( ppDefaults );
    }
    else
        SetPoolDefaults( rPool.mpPoolDefaults );

    // Copy Pool Defaults
    for (size_t n = 0; n < maUserDefaults.size(); ++n )
        if (rPool.maUserDefaults[n])
        {
            maUserDefaults[n] = rPool.maUserDefaults[n]->Clone(this); //resets kind
            maUserDefaults[n]->setUserDefault();
        }

    // Repair linkage
    if ( rPool.mpSecondary )
        SetSecondaryPool( rPool.mpSecondary->Clone().get() );
}

void SfxItemPool::SetPoolDefaults( std::vector<SfxPoolItem*>* pDefaults )
{
    DBG_ASSERT( pDefaults, "first we ask for it, and then we don't give back..." );
    DBG_ASSERT( !mpPoolDefaults, "already have Defaults" );

    mpPoolDefaults = pDefaults;
    //! if ((*mpPoolDefaults)->GetKind() != SfxItemKind::StaticDefault)
    //! FIXME: Probably doesn't work with SetItems at the end
    {
        DBG_ASSERT( (*mpPoolDefaults)[0]->GetRefCount() == 0 ||
                    IsDefaultItem( (*mpPoolDefaults)[0] ),
                    "these are not static" );
        for ( sal_uInt16 n = 0; n <= mnEnd - mnStart; ++n )
        {
            assert(  ((*mpPoolDefaults)[n]->Which() == n + mnStart)
                        && "items ids in pool-ranges and in static-defaults do not match" );
            (*mpPoolDefaults)[n]->setStaticDefault();
        }
    }
}

void SfxItemPool::ClearPoolDefaults()
{
    mpPoolDefaults = nullptr;
}

/**
 * Frees the static Defaults of the corresponding SfxItemPool instance
 * and deletes them if specified.
 *
 * The SfxItemPool instance MUST NOT BE USED after this function has
 * been called; only the dtor must be called.
 */
void SfxItemPool::ReleasePoolDefaults
(
    bool    bDelete     /*  true
                            Deletes the array as well as the single static Defaults

                            false
                            Neither deletes the array not the single static Defaults */
)


{
    DBG_ASSERT( mpPoolDefaults, "requirements not met" );
    ReleasePoolDefaults( mpPoolDefaults, bDelete );

    // mpPoolDefaults points to deleted memory if bDelete == true.
    if ( bDelete )
        mpPoolDefaults = nullptr;
}


/**
 * Frees the specified static Defaults and also deletes them, if so
 * specified.
 *
 * This method MUST be called AFTER all SfxItemPool instances (which
 * use the specified static Defaults 'pDefault') have been destroyed.
 */
void SfxItemPool::ReleasePoolDefaults
(
    std::vector<SfxPoolItem*>*
                    pDefaults,  /*  Static Defaults that are to be freed */

    bool            bDelete     /*  true
                                    Deletes the array as well as the specified
                                    static Defaults

                                    false
                                    Neither deletes the array nor the single
                                    static Defaults */
)
{
    DBG_ASSERT( pDefaults, "we first ask for it and the return nothing ..." );

    for ( auto & rpItem : *pDefaults )
    {
        assert(IsStaticDefaultItem(rpItem));
        rpItem->SetRefCount(0);
        if ( bDelete )
        {
            delete rpItem;
            rpItem = nullptr;
        }
    }

    if ( bDelete )
    {
        delete pDefaults;
        pDefaults = nullptr;
    }
}


SfxItemPool::~SfxItemPool()
{
    // Need to be deleted?
    if (!mbPreDeleteDone)//maUserDefaults.empty())
        Delete();

    if (mpMaster != nullptr && mpMaster != this)
    {
        // This condition indicates an error.
        // A mpMaster->SetSecondaryPool(...) call should have been made
        // earlier to prevent this. At this point we can only try to
        // prevent a crash later on.
        DBG_ASSERT( mpMaster == this, "destroying active Secondary-Pool" );
        if (mpMaster->mpSecondary == this)
            mpMaster->mpSecondary = nullptr;
    }
}

void SfxItemPool::SetSecondaryPool( SfxItemPool *pPool )
{
    // Reset Master in attached Pools
    if ( mpSecondary )
    {
        mpSecondary->mpMaster = mpSecondary.get();
        for ( SfxItemPool *p = mpSecondary->mpSecondary.get(); p; p = p->mpSecondary.get() )
            p->mpMaster = mpSecondary.get();
    }

    // Set Master of new Secondary Pools
    DBG_ASSERT( !pPool || pPool->mpMaster == pPool, "Secondary is present in two Pools" );
    SfxItemPool *pNewMaster = GetMasterPool() ? mpMaster : this;
    for ( SfxItemPool *p = pPool; p; p = p->mpSecondary.get() )
        p->mpMaster = pNewMaster;

    // Remember new Secondary Pool
    mpSecondary = pPool;

    CHECK_SLOTS();
}

void SfxItemPool::SetItemInfos(SfxItemInfo const*const pInfo)
{
    pItemInfos = pInfo;
    CHECK_SLOTS();
}


MapUnit SfxItemPool::GetMetric( sal_uInt16 ) const
{
    return eDefMetric;
}


void SfxItemPool::SetDefaultMetric( MapUnit eNewMetric )
{
//    assert((pImpl->eDefMetric == eNewMetric || !pImpl->mpPoolRanges) && "pool already frozen, cannot change metric");
    eDefMetric = eNewMetric;
}

MapUnit SfxItemPool::GetDefaultMetric() const
{
    return eDefMetric;
}

const OUString& SfxItemPool::GetName() const
{
    return aName;
}


bool SfxItemPool::GetPresentation
(
    const SfxPoolItem&  rItem,
    MapUnit             eMetric,
    OUString&           rText,
    const IntlWrapper&  rIntlWrapper
)   const
{
    return rItem.GetPresentation(
        SfxItemPresentation::Complete, GetMetric(rItem.Which()), eMetric, rText, rIntlWrapper );
}


rtl::Reference<SfxItemPool> SfxItemPool::Clone() const
{
    return new SfxItemPool( *this );
}


void SfxItemPool::Delete()
{
    // Already deleted?
    if (mbPreDeleteDone)//maUserDefaults.empty())
        return;
    mbPreDeleteDone = true;

    // Inform e.g. running Requests
    aBC.Broadcast( SfxHint( SfxHintId::Dying ) );

    // default items
    for (auto rItemPtr : maUserDefaults)
    {
        if (rItemPtr)
        {
#ifdef DBG_UTIL
            ClearRefCount(*rItemPtr);
#endif
            delete rItemPtr;
            rItemPtr = nullptr;
        }
    }

    maUserDefaults.clear();
    mpPoolRanges.reset();
}


void SfxItemPool::SetUserDefaultItem(const SfxPoolItem &rItem)
{
    if ( IsInRange(rItem.Which()) )
    {
        auto& rOldDefault =
            maUserDefaults[GetIndex_Impl(rItem.Which())];
        SfxPoolItem *pNewDefault = rItem.Clone(this);
        pNewDefault->setUserDefault();
        if (rOldDefault)
        {
            rOldDefault->SetRefCount(0);
            delete rOldDefault;
            rOldDefault = nullptr;
        }
        rOldDefault = pNewDefault;
    }
    else if ( mpSecondary )
        mpSecondary->SetUserDefaultItem(rItem);
    else
    {
        assert(false && "unknown WhichId - cannot set pool default");
    }
}

/**
 * Resets the default of the given WhichId back to the static Default.
 * If a pool default exists, it is removed.
 */
void SfxItemPool::ResetUserDefaultItem( sal_uInt16 nWhichId )
{
    if ( IsInRange(nWhichId) )
    {
        auto& rOldDefault =
            maUserDefaults[GetIndex_Impl(nWhichId)];
        if (rOldDefault)
        {
            rOldDefault->SetRefCount(0);
            delete rOldDefault;
            rOldDefault = nullptr;
        }
    }
    else if ( mpSecondary )
        mpSecondary->ResetUserDefaultItem(nWhichId);
    else
    {
        assert(false && "unknown WhichId - cannot reset pool default");
    }
}

const SfxPoolItem& SfxItemPool::GetUserOrPoolDefaultItem( sal_uInt16 nWhich ) const
{
    if ( !IsInRange(nWhich) )
    {
        if ( mpSecondary )
            return mpSecondary->GetUserOrPoolDefaultItem( nWhich );
        assert(!"unknown which - don't ask me for defaults");
    }

    DBG_ASSERT( mpPoolDefaults, "no defaults known - don't ask me for defaults" );
    sal_uInt16 nPos = GetIndex_Impl(nWhich);
    SfxPoolItem* pDefault = maUserDefaults[nPos];
    if ( pDefault )
        return *pDefault;
    return *(*mpPoolDefaults)[nPos];
}

SfxItemPool* SfxItemPool::GetSecondaryPool() const
{
    return mpSecondary.get();
}

/* get the last pool by following the GetSecondaryPool chain */
SfxItemPool* SfxItemPool::GetLastPoolInChain()
{
    SfxItemPool* pLast = this;
    while(pLast->GetSecondaryPool())
        pLast = pLast->GetSecondaryPool();
    return pLast;
}

SfxItemPool* SfxItemPool::GetMasterPool() const
{
    return mpMaster;
}

/**
 * This method should be called at the master pool, when all secondary
 * pools are appended to it.
 *
 * It calculates the ranges of 'which-ids' for fast construction of
 * item-sets, which contains all 'which-ids'.
 */
void SfxItemPool::FreezeIdRanges()
{
    assert(mpPoolRanges.empty() && "pool already frozen, cannot freeze twice");
    FillItemIdRanges_Impl( mpPoolRanges );
}


void SfxItemPool::FillItemIdRanges_Impl( WhichRangesContainer& pWhichRanges ) const
{
    DBG_ASSERT( mpPoolRanges.empty(), "GetFrozenRanges() would be faster!" );

    pWhichRanges.reset();

    // Merge all ranges, keeping them sorted
    for (const SfxItemPool* pPool = this; pPool; pPool = pPool->mpSecondary.get())
        pWhichRanges = pWhichRanges.MergeRange(pPool->mnStart, pPool->mnEnd);
}

const WhichRangesContainer& SfxItemPool::GetFrozenIdRanges() const
{
    return mpPoolRanges;
}

const SfxPoolItem *SfxItemPool::GetPoolDefaultItem(sal_uInt16 nWhich) const
{
    if ( !IsInRange(nWhich) )
    {
        if ( mpSecondary )
            return mpSecondary->GetPoolDefaultItem( nWhich );
        assert(false && "unknown WhichId - cannot resolve surrogate");
        return nullptr;
    }
    return (*mpPoolDefaults)[ GetIndex_Impl(nWhich) ];
}

namespace
{
    class SurrogateData_ItemSet : public SfxItemPool::SurrogateData
    {
        const SfxPoolItem*  mpItem;
        SfxItemSet*         mpSet;

    public:
        SurrogateData_ItemSet(const SfxPoolItem& rItem, SfxItemSet& rSet)
        : SfxItemPool::SurrogateData()
        , mpItem(&rItem)
        , mpSet(&rSet)
        {
        }

        SurrogateData_ItemSet(const SurrogateData_ItemSet&) = default;

        virtual const SfxPoolItem& getItem() const override
        {
            return *mpItem;
        }

        virtual const SfxPoolItem* setItem(std::unique_ptr<SfxPoolItem> aNew) override
        {
            return mpSet->Put(std::unique_ptr<SfxPoolItem>(aNew.release()));
        }
    };

    class SurrogateData_ItemHolder : public SfxItemPool::SurrogateData
    {
        SfxPoolItemHolder*  mpHolder;

    public:
        SurrogateData_ItemHolder(SfxPoolItemHolder& rHolder)
        : SfxItemPool::SurrogateData()
        , mpHolder(&rHolder)
        {
        }

        SurrogateData_ItemHolder(const SurrogateData_ItemHolder&) = default;

        virtual const SfxPoolItem& getItem() const override
        {
            return *mpHolder->getItem();
        }

        virtual const SfxPoolItem* setItem(std::unique_ptr<SfxPoolItem> aNew) override
        {
            *mpHolder = SfxPoolItemHolder(mpHolder->getPool(), aNew.release(), true);
            return mpHolder->getItem();
        }
    };
}

void SfxItemPool::iterateItemSurrogates(
    sal_uInt16 nWhich,
    const std::function<bool(SurrogateData& rCand)>& rItemCallback) const
{
    // 1st source for surrogates
    const registeredSfxItemSets& rSets(GetMasterPool()->maRegisteredSfxItemSets);

    if(!rSets.empty())
    {
        const SfxPoolItem* pItem(nullptr);
        std::vector<SurrogateData_ItemSet> aEntries;

        // NOTE: this collects the callback data in a preparing run. This
        //   is by purpose, else any write change may change the iterators
        //   used at registeredSfxItemSets. I tied with direct feed and
        //   that worked most of the time, but failed for ItemHolders due
        //   to these being changed and being re-registered. I have avoided
        //   this in SfxPoolItemHolder::operator=, but it's just a question
        //   that in some scenario someone replaces an Item even with a
        //   different type/WhichID that this will then break/crash
        for (const auto& rCand : rSets)
            if (SfxItemState::SET == rCand->GetItemState(nWhich, false, &pItem))
                aEntries.emplace_back(*pItem, *rCand);

        if (!aEntries.empty())
            for (auto& rCand : aEntries)
                if (!rItemCallback(rCand))
                    return;
    }

    // 2nd source for surrogates
    const registeredSfxPoolItemHolders& rHolders(GetMasterPool()->maRegisteredSfxPoolItemHolders);

    if (!rHolders.empty())
    {
        std::vector<SurrogateData_ItemHolder> aEntries;

        // NOTE: same as above, look there
        for (auto& rCand : rHolders)
            if (rCand->Which() == nWhich && nullptr != rCand->getItem())
                aEntries.emplace_back(*rCand);

        if (!aEntries.empty())
            for (auto& rCand : aEntries)
                if (!rItemCallback(rCand))
                    return;
    }
}

void SfxItemPool::GetItemSurrogates(ItemSurrogates& rTarget, sal_uInt16 nWhich) const
{
    rTarget.clear();

    if (0 == nWhich)
        return;

    // NOTE: This is pre-collected, in this case mainly to
    //   remove all double listings of SfxPoolItems which can
    //   of course be referenced multiple times in multiple
    //   ItemSets/ItemHolders. It comes handy that
    //   std::unordered_set does this by definition
    std::unordered_set<const SfxPoolItem*> aNewSurrogates;

    // 1st source for surrogates
    const registeredSfxItemSets& rSets(GetMasterPool()->maRegisteredSfxItemSets);
    const SfxPoolItem* pItem(nullptr);
    for (const auto& rCand : rSets)
        if (SfxItemState::SET == rCand->GetItemState(nWhich, false, &pItem))
            aNewSurrogates.insert(pItem);

    // 2nd source for surrogates
    const registeredSfxPoolItemHolders& rHolders(GetMasterPool()->maRegisteredSfxPoolItemHolders);
    for (const auto& rCand : rHolders)
        if (rCand->Which() == nWhich && nullptr != rCand->getItem())
            aNewSurrogates.insert(rCand->getItem());

    rTarget = ItemSurrogates(aNewSurrogates.begin(), aNewSurrogates.end());
}

sal_uInt16 SfxItemPool::GetWhich( sal_uInt16 nSlotId, bool bDeep ) const
{
    if ( !IsSlot(nSlotId) )
        return nSlotId;

    sal_uInt16 nCount = mnEnd - mnStart + 1;
    for ( sal_uInt16 nOfs = 0; nOfs < nCount; ++nOfs )
        if ( pItemInfos[nOfs]._nItemInfoSlotID == nSlotId )
            return nOfs + mnStart;
    if ( mpSecondary && bDeep )
        return mpSecondary->GetWhich(nSlotId);
    return nSlotId;
}


sal_uInt16 SfxItemPool::GetSlotId( sal_uInt16 nWhich ) const
{
    if ( !IsWhich(nWhich) )
        return nWhich;

    if ( !IsInRange( nWhich ) )
    {
        if ( mpSecondary )
            return mpSecondary->GetSlotId(nWhich);
        assert(false && "unknown WhichId - cannot get slot-id");
        return 0;
    }

    sal_uInt16 nSID = pItemInfos[nWhich - mnStart]._nItemInfoSlotID;
    return nSID ? nSID : nWhich;
}


sal_uInt16 SfxItemPool::GetTrueWhich( sal_uInt16 nSlotId, bool bDeep ) const
{
    if ( !IsSlot(nSlotId) )
        return 0;

    sal_uInt16 nCount = mnEnd - mnStart + 1;
    for ( sal_uInt16 nOfs = 0; nOfs < nCount; ++nOfs )
        if ( pItemInfos[nOfs]._nItemInfoSlotID == nSlotId )
            return nOfs + mnStart;
    if ( mpSecondary && bDeep )
        return mpSecondary->GetTrueWhich(nSlotId);
    return 0;
}


sal_uInt16 SfxItemPool::GetTrueSlotId( sal_uInt16 nWhich ) const
{
    if ( !IsWhich(nWhich) )
        return 0;

    if ( !IsInRange( nWhich ) )
    {
        if ( mpSecondary )
            return mpSecondary->GetTrueSlotId(nWhich);
        assert(false && "unknown WhichId - cannot get slot-id");
        return 0;
    }
    return pItemInfos[nWhich - mnStart]._nItemInfoSlotID;
}

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