summaryrefslogtreecommitdiff
path: root/configmgr/source/treemgr/setnodeimpl.cxx
blob: 10b37a7b3878eee07df246101b3503bf48698ed0 (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
1034
1035
1036
1037
1038
1039
1040
1041
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 * 
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: setnodeimpl.cxx,v $
 * $Revision: 1.26 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_configmgr.hxx"
#include <stdio.h>

#include "setnodeimpl.hxx"
#include "viewfactory.hxx"
#include "configpath.hxx"
#include "treeimpl.hxx"
#include "valuenodeimpl.hxx"
#include "nodechange.hxx"
#include "nodechangeimpl.hxx"
#include "nodeaccess.hxx"
#include "valuenodeaccess.hxx"
#include "groupnodeaccess.hxx"
#include "setnodeaccess.hxx"
#include "nodevisitor.hxx"
#include "change.hxx"
#include "viewaccess.hxx"
#include "nodeconverter.hxx" 
#include "treeactions.hxx"
#include "treechangefactory.hxx"
#include "collectchanges.hxx"
#include <osl/diagnose.h>

#ifndef INCLUDED_VECTOR
#include <vector>
#define INCLUDED_VECTOR
#endif

namespace configmgr
{
    namespace configuration
    {
//-------------------------------------------------------------------------
// initialization helpers
//-------------------------------------------------------------------------
namespace
{
    using namespace data;

    typedef SetNodeImpl::Element Element;
    
    class CollectElementTrees : SetVisitor
    {
    public:
        CollectElementTrees(view::ViewStrategyRef const& _xStrategy, 
                            TreeImpl* pParentTree, NodeOffset nPos, 
                            TreeDepth nDepth, 
                            TemplateHolder const& aTemplate, 
                            TemplateProvider const& aTemplateProvider)
        : m_aTemplate(aTemplate)
        , m_aTemplateProvider(aTemplateProvider)
        , m_xStrategy(_xStrategy)
        , m_pParentTree(pParentTree)
        , m_nPos(nPos)
        , m_nDepth(nDepth)
        {
            OSL_ENSURE(m_aTemplate.is(),"WARNING: Collecting a set without a template");				
        }

        void collect(SetNodeAccess const& _aNode) 
        { 
            this->visitElements(_aNode);
        }

        Element create(TreeAccessor const & _aElementTree) 
        { 
            OSL_ENSURE(collection.empty(),"warning: trying to reuse a full collection");
            
            collection.resize(1); // make an empty one for case of failure
            this->visitTree(_aElementTree);

            OSL_ENSURE(collection.size()==2,"warning: could not create an element");				
            return collection.back();
        }

        typedef std::vector<Element> Collection;
        Collection collection;
       protected:
           using NodeVisitor::handle;     

       private:
        Result handle(TreeAccessor const& _aElement);

        Result handle(NodeAccess const& _aNonValue);
        Result handle(ValueNodeAccess const& _aValue);

        void add(TreeAccessor const& _aNode);

        TemplateHolder		    m_aTemplate;
        TemplateProvider	    m_aTemplateProvider;
        view::ViewStrategyRef   m_xStrategy; 
        TreeImpl*	m_pParentTree;
        NodeOffset	m_nPos;
        TreeDepth	m_nDepth;
    };
    //-------------------------------------------------------------------------

    static 
    Name validatedName(Element const& aTree)
    {
        OSL_ENSURE(aTree.isValid(), "INTERNAL ERROR: Unexpected null tree constructed in set node");
        if (!aTree.isValid()) throw Exception("INTERNAL ERROR: Unexpected null tree in set node");

        OSL_ENSURE(aTree->nodeCount(), "INTERNAL ERROR: Unexpected empty (!) tree constructed in set node");
        OSL_ENSURE(aTree->isValidNode(aTree->root_()), "INTERNAL ERROR: Corrupt tree constructed in set node");

        return aTree->getSimpleRootName();
    }
    //-------------------------------------------------------------------------

    static 
    bool isInDefault(SetEntry const& _anEntry)
    {
        if (!_anEntry.isValid()) return false;

        node::Attributes aAttributes = _anEntry.getTreeView().getRootAttributes();

        bool bReplaced = aAttributes.isReplacedForUser();

        return !bReplaced;
    }
    //-------------------------------------------------------------------------
    CollectElementTrees::Result CollectElementTrees::handle(ValueNodeAccess const& _aValue)
    {
        if (m_aTemplate.is())
        {
            OSL_ENSURE(m_aTemplate->isInstanceTypeKnown(),"ERROR: Template must have a validated type when building a set.");
            OSL_ENSURE(m_aTemplate->isInstanceValue(),"ERROR: Found a value node in a Complex Template Set");

            if (!m_aTemplate->isInstanceValue())
                throw Exception("INTERNAL ERROR: Corrupt tree contains a value node within a template-set");

            UnoType aValueType = _aValue.getValueType();
            UnoType aExpectedType = m_aTemplate->getInstanceType();

            if (aValueType.getTypeClass() != aExpectedType.getTypeClass() &&
                aExpectedType.getTypeClass() != uno::TypeClass_ANY &&
                aValueType.getTypeClass() != uno::TypeClass_VOID)
            {
                OSL_ENSURE(false, "WARNING: ValueType of set node does not match the template type");
            //	throw TypeMismatch(aValueType.getTypeName(),aExpectedType.getTypeName(), "INTERNAL ERROR: - Corrupt tree contains mistyped value node within a value-set")));
            }
        }
        return CONTINUE;
    }
    //-------------------------------------------------------------------------
    CollectElementTrees::Result CollectElementTrees::handle(NodeAccess const& _aNonValue)
    {	
            { (void)_aNonValue; }               
        OSL_ENSURE(!ValueNodeAccess::isInstance(_aNonValue),"Unexpected: Value-node dispatched to wrong handler");
        if (m_aTemplate.is())
        {
            OSL_ENSURE(m_aTemplate->isInstanceTypeKnown(),"ERROR: Template must have a validated type when building a set.");
            OSL_ENSURE(!m_aTemplate->isInstanceValue(),"ERROR: Found a non-leaf node in a Value Set");

            if (m_aTemplate->isInstanceValue())
                throw Exception("INTERNAL ERROR: Corrupt tree contains a non-leaf node within a value-set");

        }
        return CONTINUE;
    }
    //-------------------------------------------------------------------------
    CollectElementTrees::Result CollectElementTrees::handle(TreeAccessor const& _aTree)
    {
        // check the node type
        Result aResult = this->visitNode( _aTree.getRootNode() );

        if (aResult == CONTINUE) this->add(_aTree);

        return aResult;
    }
    //-------------------------------------------------------------------------
    void CollectElementTrees::add(TreeAccessor const& _aTree)
    {
        node::Attributes const aAttributes = _aTree->getAttributes();

    bool bReadonly  = aAttributes.isReadonly();
    bool bInDefault = !aAttributes.isReplacedForUser();

        view::ViewStrategyRef xStrategy = !bReadonly ? m_xStrategy : view::createReadOnlyStrategy();

        ElementTreeImpl * pNewTree;
        if (m_pParentTree)
            pNewTree = new ElementTreeImpl(xStrategy, *m_pParentTree, m_nPos, _aTree,m_nDepth, m_aTemplate, m_aTemplateProvider);

        else
            pNewTree = new ElementTreeImpl(xStrategy, _aTree, m_nDepth, m_aTemplate, m_aTemplateProvider);
            
        collection.push_back( Element(pNewTree,bInDefault));
    }
}

//-------------------------------------------------------------------------
// class ElementSet
//-------------------------------------------------------------------------

bool ElementSet::hasElement(Name const& aName) const
{
    return m_aData.find(aName) != m_aData.end();
}
//-------------------------------------------------------------------------

ElementTreeData* ElementSet::getElement(Name const& aName)
{
    Data::iterator it = m_aData.find(aName);
    if (it != m_aData.end())
        return &it->second;
    else	
        return 0;
}
//-------------------------------------------------------------------------


ElementTreeData const* ElementSet::getElement(Name const& aName) const
{
    Data::const_iterator it = m_aData.find(aName);
    if (it != m_aData.end())
        return &it->second;
    else	
        return 0;
}
//-------------------------------------------------------------------------

ElementTreeData ElementSet::findElement(Name const& aName)
{
    Element aRet;

    Data::iterator it = m_aData.find(aName);
    if (it != m_aData.end())
        aRet = it->second;
        
    return aRet;
}
//-------------------------------------------------------------------------

void ElementSet::insertElement(Name const& aName, Element const& aNewEntry)
{
    bool bInserted = m_aData.insert(Data::value_type(aName, aNewEntry)).second;

    OSL_ENSURE(bInserted,"INTERNAL ERROR: Inserted set Element was already present");
    if (!bInserted) throw Exception("INTERNAL ERROR: Inserted set Element was already present");
}
//-------------------------------------------------------------------------

ElementTreeData ElementSet::replaceElement(Name const& aName, Element const& aNewEntry)
{
    OSL_ENSURE(m_aData.find(aName) != m_aData.end(),"INTERNAL ERROR: Replaced set Element is not present");

    Element& rElement = m_aData[aName];

    Element aOld = rElement;
    rElement = aNewEntry;

    return aOld;
}
//-------------------------------------------------------------------------

ElementTreeData ElementSet::removeElement(Name const& aName)
{
    Data::iterator it = m_aData.find(aName);
    OSL_ENSURE(it != m_aData.end(),"INTERNAL ERROR: Removed set Element is not present");

    Element aOld;
    if (it != m_aData.end())
    {
        aOld = it->second;
        m_aData.erase(it);
    }
    return aOld;
}
//-------------------------------------------------------------------------

//-----------------------------------------------------------------------------
// class SetEntry
//-----------------------------------------------------------------------------

SetEntry::SetEntry(ElementTreeImpl* pTree_)
: m_pTree(pTree_)
{
    OSL_ENSURE(pTree_ == 0 || pTree_->isValidNode(pTree_->root_()),
                "INTERNAL ERROR: Invalid empty tree used for SetEntry ");
}

//-----------------------------------------------------------------------------

view::ViewTreeAccess SetEntry::getTreeView() const
{
    OSL_ENSURE(isValid(), "Cannot get View Access for NULL SetEntry");
    return view::ViewTreeAccess(*m_pTree);
}

//-----------------------------------------------------------------------------
//-------------------------------------------------------------------------

//-------------------------------------------------------------------------
// class SetNodeImpl
//-------------------------------------------------------------------------

SetNodeImpl::SetNodeImpl(data::SetNodeAddress _pNodeRef,Template* pTemplate) 
: NodeImpl(reinterpret_cast<NodeAddress>(_pNodeRef))
,m_aTemplate(pTemplate)
,m_aTemplateProvider()
,m_pParentTree(0)
,m_nContextPos(0)
,m_aInit(0)
{
}
    // unbind the original
//-----------------------------------------------------------------------------

SetNodeImpl::~SetNodeImpl() 
{
}
//-----------------------------------------------------------------------------

void SetNodeImpl::rebuildFrom(SetNodeImpl& rOldData,data::SetNodeAccess const& _aNewNode)
{ 
    m_aTemplate         = rOldData.m_aTemplate;
    m_aTemplateProvider = rOldData.m_aTemplateProvider;
    m_pParentTree       = rOldData.m_pParentTree;
    m_nContextPos       = rOldData.m_nContextPos;
    m_aInit             = rOldData.m_aInit;

    if (rOldData.implHasLoadedElements())
    {
        rOldData.doTransferElements(m_aDataSet);
        implRebuildElements(_aNewNode);
        OSL_ASSERT(this->implHasLoadedElements());
    }
    else
        OSL_ASSERT(!this->implHasLoadedElements());
    
    rOldData.m_aTemplate.clear();
    rOldData.m_aTemplateProvider = TemplateProvider();
    rOldData.m_pParentTree = 0;
    rOldData.m_nContextPos = 0;

}

//-----------------------------------------------------------------------------
void SetNodeImpl::doTransferElements(ElementSet& rReplacement)
{
    m_aDataSet.swap(rReplacement);
}
//-----------------------------------------------------------------------------

void SetNodeImpl::implRebuildElements(data::SetNodeAccess const& _aNewNode)
{
    OSL_ENSURE(m_pParentTree,"Cannot rebuild set without context tree");
    rtl::Reference<view::ViewStrategy> xNewStrategy = m_pParentTree->getViewBehavior();

    for(ElementSet::Iterator it = m_aDataSet.begin(), stop = m_aDataSet.end();
    it != stop;
    ++it)
    {
        OSL_ASSERT(it->isValid());
        if (!it->isValid()) continue;

        Element aElement = *it;
        Name aName = aElement->getSimpleRootName();

        data::TreeAccessor const& aNewElementAccess = _aNewNode.getElementTree(aName);
        OSL_ASSERT(aNewElementAccess != NULL);
#ifdef DEBUG
        data::TreeAccessor const& aOldElementAccess = aElement->getOriginalTreeAccess();
        OSL_ASSERT(aOldElementAccess != NULL);
#endif

    aElement->rebuild(xNewStrategy,aNewElementAccess);
    }
}
//-----------------------------------------------------------------------------

data::SetNodeAccess SetNodeImpl::getDataAccess() const
{ 
    using namespace data;

    NodeAccess aNodeAccess = getOriginalNodeAccess();
    OSL_ASSERT(SetNodeAccess::isInstance(aNodeAccess));

    SetNodeAccess aSetAccess(aNodeAccess);
    OSL_ASSERT(aSetAccess.isValid());

    return aSetAccess;
}
//-----------------------------------------------------------------------------

TreeImpl*	SetNodeImpl::getParentTree() const 
{ 
    OSL_ENSURE(m_pParentTree,"Set Node: Parent tree not set !");
    return m_pParentTree; 
}
//-----------------------------------------------------------------------------

NodeOffset	SetNodeImpl::getContextOffset() const 
{ 
    OSL_ENSURE(m_nContextPos,"Set Node: Position within parent tree not set !");
    return m_nContextPos; 
}
//-----------------------------------------------------------------------------

bool SetNodeImpl::doIsEmpty() const 
{ 
    /*
    for(ElementSet::Iterator it = m_aDataSet.begin(), stop = m_aDataSet.end();
        it != stop;
        ++it)
    {
        if (!it->isEmpty()) 
            return false;
    }
    return true; 
    */
    return m_aDataSet.isEmpty();
}
//-------------------------------------------------------------------------

ElementTreeImpl* SetNodeImpl::doFindElement(Name const& aName)
{ 
    return m_aDataSet.findElement(aName).get(); 
}
//-------------------------------------------------------------------------
void SetNodeImpl::doDifferenceToDefaultState(SubtreeChange& _rChangeToDefault, ISubtree& _rDefaultTree)
{
    OSL_ENSURE(implHasLoadedElements(),"Should not query difference to default state for set that is not loaded");
    implDifferenceToDefaultState(_rChangeToDefault,_rDefaultTree);
}
//-----------------------------------------------------------------------------

SetElementChangeImpl* SetNodeImpl::doAdjustToAddedElement(Name const& aName, AddNode const& aAddNodeChange, Element const & aNewElement)
{
    return implAdjustToAddedElement(aName,aNewElement,aAddNodeChange.isReplacing());
}
//-------------------------------------------------------------------------

SetElementChangeImpl* SetNodeImpl::implAdjustToAddedElement(Name const& aName, Element const & aNewElement, bool _bReplacing)
{
    { (void)_bReplacing; }
    OSL_ENSURE( validatedName(aNewElement) == aName, "Unexpected Name on new element" );

    if (hasStoredElement(aName))
    {
        OSL_ENSURE( _bReplacing, "Added Element already exists - replacing" );

        Element aOldElement = this->replaceElement(aName,aNewElement);

        return implCreateReplace(aName,aNewElement,aOldElement);
    }
    else
    {
        OSL_ENSURE( !_bReplacing, "Replaced Element doesn't exist - simply adding" );
        this->insertElement(aName,aNewElement);

        return implCreateInsert(aName,aNewElement);
    }
}
//-------------------------------------------------------------------------

SetElementChangeImpl* SetNodeImpl::doAdjustToRemovedElement(Name const& aName, RemoveNode const& /*aRemoveNodeChange*/)
{
    return implAdjustToRemovedElement(aName);
}
//-------------------------------------------------------------------------

SetElementChangeImpl* SetNodeImpl::implAdjustToRemovedElement(Name const& aName)
{
    if (Element* pOriginal = getStoredElement(aName))
    {
        Element aOldElement = *pOriginal;
        this->removeElement(aName);

        return implCreateRemove(aName,aOldElement);
    }
    else
    {
        OSL_ENSURE( false, "Removed Element doesn't exist - ignoring" );
        return 0;
    }
}
//-------------------------------------------------------------------------

SetElementChangeImpl* SetNodeImpl::implCreateInsert(Name const& aName, Element const& aNewElement) const
{
    Path::Component aFullName = Path::makeCompositeName(aName, this->getElementTemplate()->getName());

    SetElementChangeImpl* pRet = new SetInsertImpl(aFullName, aNewElement.tree, true);
    pRet->setTarget( getParentTree(), getContextOffset() );
    return pRet;
}
//-------------------------------------------------------------------------

SetElementChangeImpl* SetNodeImpl::implCreateReplace(Name const& aName, Element const& aNewElement, Element const& aOldElement) const
{
    Path::Component aFullName = Path::makeCompositeName(aName, this->getElementTemplate()->getName());

    SetElementChangeImpl* pRet = new SetReplaceImpl(aFullName, aNewElement.tree, aOldElement.tree);
    pRet->setTarget( getParentTree(), getContextOffset() );
    return pRet;
}
//-------------------------------------------------------------------------

SetElementChangeImpl* SetNodeImpl::implCreateRemove(Name const& aName, Element const& aOldElement) const
{
    Path::Component aFullName = Path::makeCompositeName(aName, this->getElementTemplate()->getName());

    SetElementChangeImpl* pRet = new SetRemoveImpl(aFullName, aOldElement.tree);
    pRet->setTarget( getParentTree(), getContextOffset() );
    return pRet;
}
//-------------------------------------------------------------------------

void SetNodeImpl::insertElement(Name const& aName, Element const& aNewElement) 
{ 
    attach(aNewElement,aName);
    try 
    { 
        m_aDataSet.insertElement(aName,aNewElement); 
    }
    catch (std::exception&) 
    { 
        detach(aNewElement); 
        throw; 
    }
}
//-------------------------------------------------------------------------

Element	SetNodeImpl::replaceElement(Name const& aName, Element const& aNewElement) 
{ 
    attach(aNewElement,aName);
    try 
    { 
        Element aOldElement = m_aDataSet.replaceElement(aName,aNewElement);
        detach(aOldElement); 
        return aOldElement;
    }
    catch (std::exception&) 
    { 
        detach(aNewElement); 
        throw; 
    }
}
//-------------------------------------------------------------------------

Element	SetNodeImpl::removeElement(Name const& aName)
{ 
    Element aOldElement = m_aDataSet.removeElement(aName);
    detach(aOldElement); 
    return aOldElement;
}
//-------------------------------------------------------------------------
SetNodeVisitor::Result	SetNodeImpl::doDispatchToElements(SetNodeVisitor& aVisitor)
{
    SetNodeVisitor::Result eRet = SetNodeVisitor::CONTINUE;
    for(ElementSet::Iterator it = m_aDataSet.begin(), stop = m_aDataSet.end();
        it != stop && eRet != SetNodeVisitor::DONE; 
        ++it)
    {
        eRet = aVisitor.visit( SetEntry(it->get()) ); 
    }
    return eRet;
}
//-----------------------------------------------------------------------------

void SetNodeImpl::attach(Element const& aNewElement, Name const& aName)
{ 
    // check for name (this also reject NULLs, therefore it should go first)
    Name aActualName = validatedName(aNewElement);

    TreeImpl*	pParentContext	= getParentTree();
    NodeOffset	nParentOffset	= getContextOffset();

    OSL_ENSURE(nParentOffset != 0 && pParentContext != 0,"INTERNAL ERROR: Set has no context");

    bool bHasContext = (aNewElement->getContextTree() != 0);

    if (bHasContext)
    {	
        if (aNewElement->getContextTree() != pParentContext)
        {
            OSL_ENSURE(false,"INTERNAL ERROR: New set element belongs to another context tree" );
            throw Exception("INTERNAL ERROR: New set element belongs to another context tree" );
        }
        if (aNewElement->getContextNode() != nParentOffset)
        {
            OSL_ENSURE(false,"INTERNAL ERROR: New set element belongs to another context node" );
            throw Exception("INTERNAL ERROR: New set element belongs to another context node" );
        }
    }
    else
    {
        OSL_ENSURE(aNewElement->getContextNode() == 0, "INTERNAL ERROR: New element has context position without a parent");
        aNewElement->moveTree(pParentContext,nParentOffset); 
    }

    // check for and correct a misnomer - do only after parenthood is assured (else we don't own it anyways)
    if (aName != aActualName)
    {
    //	OSL_ENSURE(aActualName.isEmpty(), "WARNING: Wrongly named tree inserted in set node");
        aNewElement->renameTree(aName);
        
        aActualName = validatedName(aNewElement);
        if (aName !=aActualName )
        {
            OSL_ENSURE(false, "INTERNAL ERROR: Cannot rename tree in set node");
            throw Exception("INTERNAL ERROR: Cannot rename tree for insertion into set node");
        }
    }

//	if (bCommit) aNewElement->attachTo( directSetAccess_hack(getOriginalNodeAddress()), aName );
}
//-------------------------------------------------------------------------

void SetNodeImpl::detach(Element const& aOldElement)
{ 
    if (aOldElement.isValid())
    {
        aOldElement->detachTree();
//		if (bCommit) aOldElement->detachFrom( directSetAccess_hack(getOriginalNodeAddress()), validatedName(aOldElement));
    }
}
//-------------------------------------------------------------------------

Element SetNodeImpl::entryToElement(SetEntry const& _anEntry)
{ 
    ElementTreeImpl * pTree = _anEntry.tree();
    return Element(pTree, isInDefault(_anEntry));
}
//-------------------------------------------------------------------------


SetElementChangeImpl* SetNodeImpl::doAdjustChangedElement(NodeChangesInformation& rLocalChanges, Name const& aName, Change const& _aElementChange)
{
    SetElementChangeImpl* pThisChange  = NULL;
    
    if (Element* pElement = getStoredElement(aName))
    {
        OSL_ASSERT(pElement->isValid());

        if (_aElementChange.ISA(SubtreeChange))
        {
            //OSL_ENSURE( !containsValues(), "Unexpected kind of change: Tree change applied to value set element" );

            SubtreeChange const& aSubtreeChange = static_cast<SubtreeChange const&>(_aElementChange);
            // recurse to element tree
            view::Tree aElementTree(**pElement);

            view::getViewBehavior(aElementTree)->adjustToChanges(rLocalChanges, view::getRootNode(aElementTree), aSubtreeChange);
        }
        else if ( _aElementChange.ISA(ValueChange) )
        {
            //OSL_ENSURE( containsValues(), "Unexpected kind of change: Value change applied to tree set element" );

            ValueChange const& aValueChange = static_cast<ValueChange const&>(_aElementChange);

            // make an element for the old element
            std::auto_ptr<ValueNode> aOldNode = OTreeNodeConverter().createCorrespondingNode(aValueChange);
            aOldNode->setValue(aValueChange.getOldValue());

            bool bWasDefault = (aValueChange.getMode() == ValueChange::wasDefault);

            std::auto_ptr<INode> aBasePtr(aOldNode.release());
            Name aElementTypeName = getElementTemplate()->getName();
            data::TreeSegment aOldBaseTree = data::TreeSegment::createNew( aBasePtr, aElementTypeName.toString() );

            ElementTreeHolder aOldElement = new ElementTreeImpl(aOldBaseTree, getElementTemplate(), getTemplateProvider());

            OSL_ASSERT(aOldBaseTree.is()); // the tree took ownership
            OSL_ASSERT(aOldElement->isFree()); // the tree is free-floating

            pThisChange = implCreateReplace(aName,*pElement,Element(aOldElement,bWasDefault));
        }
        else
            OSL_ENSURE( false, "Unexpected kind of change to set element" );

    }
    else
    {
        // could be changed to do an insert instead (?)
        OSL_ENSURE( false, "Changed Element doesn't exist - (and not adding now)" );
    }
    return pThisChange;
}
//-------------------------------------------------------------------------

bool SetNodeImpl::implHasLoadedElements() const 
{
    return m_aInit == 0; // cannot check whether init was called though ...
}
//-----------------------------------------------------------------------------

void SetNodeImpl::initElements(TemplateProvider const& aTemplateProvider,TreeImpl& rParentTree,NodeOffset nPos,TreeDepth nDepth)
{
    OSL_ENSURE(m_pParentTree == 0 || m_pParentTree == &rParentTree,	"WARNING: Set Node: Changing parent");
    OSL_ENSURE(m_nContextPos == 0 || m_nContextPos == nPos,			"WARNING: Set Node: Changing location within parent");
    m_pParentTree = &rParentTree;
    m_nContextPos = nPos;

    OSL_ENSURE(!m_aTemplateProvider.isValid() || !implHasLoadedElements(),"ERROR: Reinitializing set"); //doClearElements();
    OSL_ASSERT(doIsEmpty()); //doClearElements();

    OSL_ENSURE(!m_aTemplate.is() || m_aTemplate->isInstanceTypeKnown(),"ERROR: Need a type-validated template to fill a set");
    OSL_ENSURE(aTemplateProvider.isValid() || nDepth == 0 || m_aTemplate->isInstanceValue(), "ERROR: Need a template provider to fill a non-primitive set");

    if (nDepth > 0) // dont set a template provider for zero-depth sets
    {
        m_aInit = nDepth;
        m_aTemplateProvider = aTemplateProvider;
    }
}
//-----------------------------------------------------------------------------

bool SetNodeImpl::implLoadElements() 
{
    if (m_aInit > 0)
    {
    OSL_ENSURE(!getElementTemplate().is() || getElementTemplate()->isInstanceTypeKnown(),"ERROR: Need a type-validated template to fill a set");
    OSL_ENSURE(getTemplateProvider().isValid() || getElementTemplate()->isInstanceValue(), "ERROR: Need a template provider to fill a non-primitive set");

        TreeDepth nDepth = m_aInit;
    implInitElements(this->getDataAccess(),nDepth);
    m_aInit = 0;
    }
    OSL_ASSERT(implHasLoadedElements());

    return m_aInit == 0;
}
//-----------------------------------------------------------------------------

void SetNodeImpl::implEnsureElementsLoaded() 
{
    if (!implLoadElements())
        throw ConstraintViolation("Trying to access set elements beyond the loaded nestíng level");
}
//-----------------------------------------------------------------------------

void SetNodeImpl::implInitElements( data::SetNodeAccess const& _aNode, TreeDepth nDepth)
{
    TreeImpl* pThisTree = getParentTree();

    OSL_ENSURE(pThisTree,"Cannot load elements of a set that has no parent tree");

    CollectElementTrees aCollector( pThisTree->getViewBehavior(), pThisTree, getContextOffset(),
                                    nDepth, getElementTemplate(), getTemplateProvider() );
    aCollector.collect(_aNode);

    typedef CollectElementTrees::Collection::const_iterator Iter;
    for(Iter it = aCollector.collection.begin(), stop = aCollector.collection.end();
        it != stop; ++it)
    {
        implInitElement(implValidateElement(*it));
    }
}
//-------------------------------------------------------------------------

void SetNodeImpl::implInitElement(Element const& aNewElement) 
{ 
    OSL_PRECOND(aNewElement.isValid(),"INTERNAL ERROR: Set element is NULL");
    OSL_ENSURE(!aNewElement->isFree(),"INTERNAL ERROR: Set element is free-floating");

    OSL_ENSURE(aNewElement->getContextTree() == getParentTree(),"INTERNAL ERROR: Set element has wrong context tree");
    OSL_ENSURE(aNewElement->getContextNode() == getContextOffset(),"INTERNAL ERROR: Set element has wrong context node");

    Name aName = validatedName(aNewElement);

    OSL_ENSURE(!aName.isEmpty(),"INTERNAL ERROR: Unnamed element in set");
    OSL_ENSURE(m_aDataSet.getElement(aName) == 0,"INTERNAL ERROR: Duplicate element name in set");

    m_aDataSet.insertElement(aName,aNewElement); 
}
//-------------------------------------------------------------------------

Element SetNodeImpl::makeAdditionalElement(rtl::Reference<view::ViewStrategy> const& _xStrategy, AddNode const& aAddNodeChange, TreeDepth nDepth)
{
    OSL_ENSURE(aAddNodeChange.wasInserted(), "Cannot integrate element that is not in tree yet");

    data::TreeAddress aAddedTree = aAddNodeChange.getInsertedTree();
    // need 'unsafe', because ownership would be gone when notifications are sent
    if (aAddedTree != NULL)
    {
        // OSL_ENSURE( pNode->ISA(ISubtree), "Type mismatch when adjusting to update: value element found in tree set");

        CollectElementTrees aCollector( _xStrategy, getParentTree(), getContextOffset(),
                                        nDepth, getElementTemplate(), getTemplateProvider() );

        data::TreeAccessor aElementAccess(aAddedTree);

        return implValidateElement(aCollector.create(aElementAccess));
    }

    return Element();
}
//-------------------------------------------------------------------------

Element SetNodeImpl::implValidateElement(Element const& aNewElement)
{
    TemplateHolder aTemplate = getElementTemplate();
    OSL_ENSURE(aTemplate.is(),"INTERNAL ERROR: No template in set node");
    OSL_ENSURE(aTemplate->isInstanceTypeKnown(),"INTERNAL ERROR: Unspecifed template in set node");

    OSL_ENSURE(aNewElement.isValid(),"INTERNAL ERROR: Unexpected NULL element in set node");
    if (aNewElement.isValid())
    {
        if (aTemplate->isInstanceValue())
        {
            if (aNewElement->nodeCount() == 0)
            {
                OSL_ENSURE(false,"INTERNAL ERROR: Invalid (empty) element tree in value set");
                throw Exception("INTERNAL ERROR: Invalid (empty) element tree in value set");
            }
            if (aNewElement->nodeCount() > 1)
            {
                OSL_ENSURE(false,"INTERNAL ERROR: Complex element tree in value set");
                throw Exception("INTERNAL ERROR: Complex element tree in value set");
            }

            view::Node aElementRoot = view::getRootNode( view::Tree(*aNewElement) );

            OSL_ENSURE(aElementRoot.isValueNode(),"INTERNAL ERROR: Inserting complex type into value set node");
             
            view::ValueNode aValueNode(aElementRoot);
            UnoType aValueType = aValueNode.get_impl()->getValueType();

            OSL_ENSURE(	aValueType.getTypeClass() != uno::TypeClass_INTERFACE,
                        "INTERNAL ERROR: Inserting complex type into value set node");

            UnoType aElementType	= aTemplate->getInstanceType();

            if (aValueType != aElementType)
            {
                // handle 'Any'
                if (aElementType.getTypeClass() != uno::TypeClass_ANY)
                {
                    OSL_ENSURE(false,"INTERNAL ERROR:  ´Wrong value type inserting into value set");
                    throw TypeMismatch(aValueType.getTypeName(), aElementType.getTypeName(),
                                        "- INTERNAL ERROR: Mistyped element in value set");
                }
            }
        }
        else // a complete tree
        {
            // TODO: add some validation here
            if (!aNewElement->isTemplateInstance())
            {
                throw TypeMismatch(	OUString(RTL_CONSTASCII_USTRINGPARAM("<Unknown> [Missing Template]")),
                                    aTemplate->getName().toString(),
                                    " - Trying to insert element without template into set");
            }
            if (!aNewElement->isInstanceOf(aTemplate))
            {
                throw TypeMismatch(	aNewElement->getTemplate()->getPathString(),
                                    aTemplate->getPathString(),
                                    " - Trying to insert element with wrong template into set");
            }
        }
    }
    return aNewElement;
}
//-------------------------------------------------------------------------

namespace
{
    //-------------------------------------------------------------------------
    class DiffToDefault : data::SetVisitor
    {
        SubtreeChange&          m_rChange;
        ISubtree&               m_rDefaultTree;
        OTreeChangeFactory&     m_rChangeFactory;
    public:
        explicit
        DiffToDefault(SubtreeChange& _rChange, ISubtree& _rDefaultTree)
        : m_rChange(_rChange)
        , m_rDefaultTree(_rDefaultTree)
        , m_rChangeFactory( getDefaultTreeChangeFactory() )
        {   
        }

        void diff(data::SetNodeAccess const& _aActualTree)
        { 
            translate(m_rDefaultTree);
            visitElements(_aActualTree); 
        }
    protected:
        using NodeVisitor::handle;

    private:
        void translate(ISubtree& _rDefaultTree);
        void handleDefault(data::TreeSegment const & _pDefaultElement);
        void handleActual(data::TreeAccessor const& _aElement);

        virtual Result handle(data::TreeAccessor const& _aElement)   
        { handleActual(_aElement); return CONTINUE; }
    };
    //-------------------------------------------------------------------------

    void DiffToDefault::translate(ISubtree& _rDefaultTree)
    {
        typedef CollectNames::NameList::const_iterator NameIter;

        OUString aTypeName = _rDefaultTree.getElementTemplateName();
        OSL_ENSURE(aTypeName.getLength(),"Cannot get element type for default set");

        CollectNames aCollector;
        aCollector.applyToChildren(_rDefaultTree);
        
        CollectNames::NameList const& aNames = aCollector.list();

        for(NameIter it = aNames.begin(); it != aNames.end(); ++it)
        {
            std::auto_ptr<INode> aChild = _rDefaultTree.removeChild(*it);
            handleDefault( data::TreeSegment::createNew(aChild,aTypeName) );
        }

    }
    //-------------------------------------------------------------------------

    void DiffToDefault::handleDefault(data::TreeSegment const &_pDefaultElement)
    {
        OSL_PRECOND(_pDefaultElement.is(), "Unexpected NULL default node");
        if (!_pDefaultElement.is()) return;

        OUString sName = _pDefaultElement.getName().toString();

        OSL_ENSURE(_pDefaultElement.getTreeData()->getAttributes().isDefault(), "Missing default state on default element tree");
        OSL_ENSURE(_pDefaultElement.getSegmentRootNode()->isDefault(), "Missing default attribute on default node");

        std::auto_ptr<AddNode> pAddIt( m_rChangeFactory.createAddNodeChange(_pDefaultElement, sName,true) );

        m_rChange.addChange(base_ptr(pAddIt));
    }
    //-------------------------------------------------------------------------

// -----------------------------------------------------------------------------	
    void DiffToDefault::handleActual(data::TreeAccessor const& _aElement)
    {
        bool bDefaultElement = _aElement.getRootNode()->isDefault();

        OUString sName = _aElement.getName().toString();

        if (Change* pDefaultNode = m_rChange.getChange(sName) )
        {

            if (pDefaultNode->ISA(AddNode))
            {
                AddNode* pAddIt = static_cast<AddNode*>(pDefaultNode);
                if (bDefaultElement)
                {
                    data::TreeSegment aDefaultTree = pAddIt->getNewTree();
                    m_rDefaultTree.addChild( aDefaultTree.cloneData(true) );
                    
                    // no change needed - remove the change and recover the default
                    m_rChange.removeChange(sName);
                }
                else 
                {
                   // OSL_ENSURE(!pAddIt->getReplacedNode().is(), "Duplicate node name in actual tree");

                   // pAddIt->expectReplacedNode(pActualNode);
                }
            }
            else
            {
                // should never happen
                OSL_ENSURE(pDefaultNode->ISA(RemoveNode), "Unexpected node type found in translated default tree");
                OSL_ENSURE(!pDefaultNode->ISA(RemoveNode), "Duplicate node name in actual tree");

                if (bDefaultElement) m_rChange.removeChange(sName);
            }
        }
        else
        {
            OSL_ENSURE(!bDefaultElement, "Node marked 'default' not found in actual default data");

            std::auto_ptr<RemoveNode> pRemoveIt( m_rChangeFactory.createRemoveNodeChange(sName,true) );
            // pRemoveIt->expectRemovedNode(pActualNode);
            m_rChange.addChange(base_ptr(pRemoveIt));
        }
    }
//-----------------------------------------------------------------------------
}
//-----------------------------------------------------------------------------
void SetNodeImpl::implDifferenceToDefaultState(SubtreeChange& _rChangeToDefault, ISubtree& _rDefaultTree) const
{
    DiffToDefault(_rChangeToDefault,_rDefaultTree).diff( getDataAccess() );
}
//-----------------------------------------------------------------------------
void SetNodeImpl::convertChanges(NodeChangesInformation& rLocalChanges, SubtreeChange const& rExternalChange, 
                                 TreeDepth nDepth)
{
    OSL_ASSERT(nDepth > 0);

    if (TreeImpl* pParentTree = this->getParentTree())
    {
        NodeOffset nNode = getContextOffset();

        OSL_ENSURE(pParentTree->isValidNode(nNode), "Invalid context node in Set");
        OSL_ENSURE(view::Node(*pParentTree, nNode).get_impl() == this, 
                    "Wrong context node in Set");

        CollectChanges aCollector(rLocalChanges, *pParentTree, nNode, getElementTemplate(), nDepth);

        aCollector.collectFromChildren(rExternalChange);
    }
    else
        OSL_ENSURE(false, "Missing context tree in Set");
}
//-----------------------------------------------------------------------------

    }
}