Salome HOME
49e922a804d8cb4a2cab873bcdf69955d2e01b77
[modules/shaper.git] / src / Model / Model_Objects.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
2
3 // File:        Model_Objects.cxx
4 // Created:     15 May 2015
5 // Author:      Mikhail PONIKAROV
6
7 #include <Model_Objects.h>
8 #include <Model_Data.h>
9 #include <Model_Document.h>
10 #include <Model_Events.h>
11 #include <Model_Session.h>
12 #include <Model_ResultPart.h>
13 #include <Model_ResultConstruction.h>
14 #include <Model_ResultBody.h>
15 #include <Model_ResultCompSolid.h>
16 #include <Model_ResultGroup.h>
17 #include <Model_ResultParameter.h>
18 #include <ModelAPI_Validator.h>
19 #include <ModelAPI_CompositeFeature.h>
20 #include <ModelAPI_Tools.h>
21
22 #include <Events_Loop.h>
23 #include <Events_Error.h>
24
25 #include <TDataStd_Integer.hxx>
26 #include <TDataStd_Comment.hxx>
27 #include <TDF_ChildIDIterator.hxx>
28 #include <TDataStd_ReferenceArray.hxx>
29 #include <TDataStd_HLabelArray1.hxx>
30 #include <TDataStd_Name.hxx>
31 #include <TDF_Reference.hxx>
32 #include <TDF_ChildIDIterator.hxx>
33 #include <TDF_LabelMapHasher.hxx>
34 #include <TDF_LabelMap.hxx>
35 #include <TDF_ListIteratorOfLabelList.hxx>
36
37 static const int TAG_OBJECTS = 2;  // tag of the objects sub-tree (features, results)
38
39 // feature sub-labels
40 static const int TAG_FEATURE_ARGUMENTS = 1;  ///< where the arguments are located
41 static const int TAG_FEATURE_RESULTS = 2;  ///< where the results are located
42
43 ///
44 /// 0:1:2 - where features are located
45 /// 0:1:2:N:1 - data of the feature N
46 /// 0:1:2:N:2:K:1 - data of the K result of the feature N
47
48 Model_Objects::Model_Objects(TDF_Label theMainLab) : myMain(theMainLab)
49 {
50 }
51
52 void Model_Objects::setOwner(DocumentPtr theDoc)
53 {
54   myDoc = theDoc;
55   // update all fields and recreate features and result objects if needed
56   TDF_LabelList aNoUpdated;
57   synchronizeFeatures(aNoUpdated, true, true);
58   myHistory.clear();
59 }
60
61 Model_Objects::~Model_Objects()
62 {
63   // delete all features of this document
64   Events_Loop* aLoop = Events_Loop::loop();
65   // erase one by one to avoid access from the feature destructor itself from he map
66   while(!myFeatures.IsEmpty()) {
67     NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFeaturesIter(myFeatures);
68     FeaturePtr aFeature = aFeaturesIter.Value();
69     static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
70     ModelAPI_EventCreator::get()->sendDeleted(myDoc, ModelAPI_Feature::group());
71     ModelAPI_EventCreator::get()->sendUpdated(aFeature, EVENT_DISP);
72     aFeature->eraseResults();
73     aFeature->erase();
74     myFeatures.UnBind(aFeaturesIter.Key());
75   }
76   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
77   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
78
79 }
80
81 /// Appends to the array of references a new referenced label
82 static void AddToRefArray(TDF_Label& theArrayLab, TDF_Label& theReferenced, TDF_Label& thePrevLab)
83 {
84   Handle(TDataStd_ReferenceArray) aRefs;
85   if (!theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
86     aRefs = TDataStd_ReferenceArray::Set(theArrayLab, 0, 0);
87     aRefs->SetValue(0, theReferenced);
88   } else {  // extend array by one more element
89     Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
90                                                                         aRefs->Upper() + 1);
91     int aPassedPrev = 0; // prev feature is found and passed
92     if (thePrevLab.IsNull()) { // null means that inserted feature must be the first
93       aNewArray->SetValue(aRefs->Lower(), theReferenced);
94       aPassedPrev = 1;
95     }
96     for (int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
97       aNewArray->SetValue(a + aPassedPrev, aRefs->Value(a));
98       if (!aPassedPrev && aRefs->Value(a).IsEqual(thePrevLab)) {
99         aPassedPrev = 1;
100         aNewArray->SetValue(a + 1, theReferenced);
101       }
102     }
103     if (!aPassedPrev) // not found: unknown situation
104       aNewArray->SetValue(aRefs->Upper() + 1, theReferenced);
105     aRefs->SetInternalArray(aNewArray);
106   }
107 }
108
109 void Model_Objects::addFeature(FeaturePtr theFeature, const FeaturePtr theAfterThis)
110 {
111   if (!theFeature->isAction()) {  // do not add action to the data model
112     TDF_Label aFeaturesLab = featuresLabel();
113     TDF_Label aFeatureLab = aFeaturesLab.NewChild();
114     // store feature in the features array: before "initData" because in macro features
115     // in initData it creates new features, appeared later than this
116     TDF_Label aPrevFeateureLab;
117     if (theAfterThis.get()) { // searching for the previous feature label
118       std::shared_ptr<Model_Data> aPrevData = 
119         std::dynamic_pointer_cast<Model_Data>(theAfterThis->data());
120       if (aPrevData.get()) {
121         aPrevFeateureLab = aPrevData->label().Father();
122       }
123     }
124     AddToRefArray(aFeaturesLab, aFeatureLab, aPrevFeateureLab);
125
126     // keep the feature ID to restore document later correctly
127     TDataStd_Comment::Set(aFeatureLab, theFeature->getKind().c_str());
128     myFeatures.Bind(aFeatureLab, theFeature);
129     // must be after binding to the map because of "Box" macro feature that 
130     // creates other features in "initData"
131     initData(theFeature, aFeatureLab, TAG_FEATURE_ARGUMENTS);
132     // event: feature is added
133     static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
134     ModelAPI_EventCreator::get()->sendUpdated(theFeature, anEvent);
135     theFeature->setDisabled(false); // by default created feature is enabled
136     updateHistory(ModelAPI_Feature::group());
137   } else { // make feature has not-null data anyway
138     theFeature->setData(Model_Data::invalidData());
139     theFeature->setDoc(myDoc);
140   }
141 }
142
143 /// Appends to the array of references a new referenced label.
144 /// If theIndex is not -1, removes element at this index, not theReferenced.
145 /// \returns the index of removed element
146 static int RemoveFromRefArray(TDF_Label theArrayLab, TDF_Label theReferenced, 
147   const int theIndex = -1)
148 {
149   int aResult = -1;  // no returned
150   Handle(TDataStd_ReferenceArray) aRefs;
151   if (theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
152     if (aRefs->Length() == 1) {  // just erase an array
153       if ((theIndex == -1 && aRefs->Value(0) == theReferenced) || theIndex == 0) {
154         theArrayLab.ForgetAttribute(TDataStd_ReferenceArray::GetID());
155       }
156       aResult = 0;
157     } else {  // reduce the array
158       Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
159                                                                           aRefs->Upper() - 1);
160       int aCount = aRefs->Lower();
161       for (int a = aCount; a <= aRefs->Upper(); a++, aCount++) {
162         if ((theIndex == -1 && aRefs->Value(a) == theReferenced) || theIndex == a) {
163           aCount--;
164           aResult = a;
165         } else {
166           aNewArray->SetValue(aCount, aRefs->Value(a));
167         }
168       }
169       aRefs->SetInternalArray(aNewArray);
170     }
171   }
172   return aResult;
173 }
174
175 void Model_Objects::refsToFeature(FeaturePtr theFeature,
176   std::set<std::shared_ptr<ModelAPI_Feature> >& theRefs, const bool isSendError)
177 {
178   // check the feature: it must have no depended objects on it
179   // the dependencies can be in the feature results
180   std::list<ResultPtr>::const_iterator aResIter = theFeature->results().cbegin();
181   for(; aResIter != theFeature->results().cend(); aResIter++) {
182     ResultPtr aResult = (*aResIter);
183     std::shared_ptr<Model_Data> aData = 
184       std::dynamic_pointer_cast<Model_Data>(aResult->data());
185     if (aData.get() != NULL) {
186       const std::set<AttributePtr>& aRefs = aData->refsToMe();
187       std::set<AttributePtr>::const_iterator aRefIt = aRefs.begin(), aRefLast = aRefs.end();
188       for(; aRefIt != aRefLast; aRefIt++) {
189         FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRefIt)->owner());
190         if (aFeature.get() != NULL)
191           theRefs.insert(aFeature);
192       }
193     }
194   }
195   // the dependencies can be in the feature itself
196   std::shared_ptr<Model_Data> aData = 
197       std::dynamic_pointer_cast<Model_Data>(theFeature->data());
198   if (aData && !aData->refsToMe().empty()) {
199     const std::set<AttributePtr>& aRefs = aData->refsToMe();
200     std::set<AttributePtr>::const_iterator aRefIt = aRefs.begin(), aRefLast = aRefs.end();
201     for(; aRefIt != aRefLast; aRefIt++) {
202       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRefIt)->owner());
203       if (aFeature.get() != NULL)
204         theRefs.insert(aFeature);
205     }
206   }
207
208   if (!theRefs.empty() && isSendError) {
209     Events_Error::send(
210       "Feature '" + theFeature->data()->name() + "' is used and can not be deleted");
211   }
212 }
213
214 void Model_Objects::removeFeature(FeaturePtr theFeature)
215 {
216   std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theFeature->data());
217   if (aData && aData->isValid()) {
218     // checking that the sub-element of composite feature is removed: if yes, inform the owner
219     std::set<std::shared_ptr<ModelAPI_Feature> > aRefs;
220     refsToFeature(theFeature, aRefs, false);
221     std::set<std::shared_ptr<ModelAPI_Feature> >::iterator aRefIter = aRefs.begin();
222     for(; aRefIter != aRefs.end(); aRefIter++) {
223       std::shared_ptr<ModelAPI_CompositeFeature> aComposite = 
224         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(*aRefIter);
225       if (aComposite.get()) {
226         aComposite->removeFeature(theFeature);
227       }
228     }
229     // this must be before erase since theFeature erasing removes all information about
230     // the feature results and groups of results
231     // To reproduce: create sketch, extrusion, remove sketch => constructions tree is not updated
232     clearHistory(theFeature);
233     // erase fields
234     theFeature->erase();
235
236     TDF_Label aFeatureLabel = aData->label().Father();
237     if (myFeatures.IsBound(aFeatureLabel))
238       myFeatures.UnBind(aFeatureLabel);
239
240     static Events_ID EVENT_DISP = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
241     ModelAPI_EventCreator::get()->sendUpdated(theFeature, EVENT_DISP);
242     // erase all attributes under the label of feature
243     aFeatureLabel.ForgetAllAttributes();
244     // remove it from the references array
245     RemoveFromRefArray(featuresLabel(), aFeatureLabel);
246     // event: feature is deleted
247     ModelAPI_EventCreator::get()->sendDeleted(theFeature->document(), ModelAPI_Feature::group());
248     // the redisplay signal should be flushed in order to erase the feature presentation in the viewer
249     Events_Loop::loop()->flush(EVENT_DISP);
250     updateHistory(ModelAPI_Feature::group());
251   }
252 }
253
254 void Model_Objects::moveFeature(FeaturePtr theMoved, FeaturePtr theAfterThis)
255 {
256   TDF_Label aFeaturesLab = featuresLabel();
257   Handle(TDataStd_ReferenceArray) aRefs;
258   if (!aFeaturesLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
259     return;
260   TDF_Label anAfterLab, aMovedLab = 
261     std::dynamic_pointer_cast<Model_Data>(theMoved->data())->label().Father();
262   if (theAfterThis.get())
263     anAfterLab = std::dynamic_pointer_cast<Model_Data>(theAfterThis->data())->label().Father();
264
265   Handle(TDataStd_HLabelArray1) aNewArray = 
266     new TDataStd_HLabelArray1(aRefs->Lower(), aRefs->Upper());
267   int aPassedMovedFrom = 0; // the prev feature location is found and passed
268   int aPassedMovedTo = 0; // the feature is added and this location is passed
269   if (!theAfterThis.get()) { // null means that inserted feature must be the first
270     aNewArray->SetValue(aRefs->Lower(), aMovedLab);
271     aPassedMovedTo = 1;
272   }
273   for (int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
274     if (aPassedMovedTo == 0 && aRefs->Value(a) == anAfterLab) { // add two
275       aPassedMovedTo++;
276       aNewArray->SetValue(a - aPassedMovedFrom, anAfterLab);
277       if (a + 1 - aPassedMovedFrom <= aRefs->Upper())
278         aNewArray->SetValue(a + 1 - aPassedMovedFrom, aMovedLab);
279     } else if (aPassedMovedFrom == 0 && aRefs->Value(a) == aMovedLab) { // skip
280       aPassedMovedFrom++;
281     } else { // just copy one
282       if (a - aPassedMovedFrom + aPassedMovedTo <= aRefs->Upper())
283         aNewArray->SetValue(a - aPassedMovedFrom + aPassedMovedTo, aRefs->Value(a));
284     }
285   }
286   if (!aPassedMovedFrom || !aPassedMovedTo) {// not found: unknown situation
287     if (!aPassedMovedFrom) {
288       static std::string aMovedFromError("The moved feature is not found");
289       Events_Error::send(aMovedFromError);
290     } else {
291       static std::string aMovedToError("The 'after' feature for movement is not found");
292       Events_Error::send(aMovedToError);
293     }
294     return;
295   }
296   // store the new array
297   aRefs->SetInternalArray(aNewArray);
298   // update the feature and the history
299   clearHistory(theMoved);
300   static Events_ID EVENT_UPD = Events_Loop::loop()->eventByName(EVENT_OBJECT_UPDATED);
301   ModelAPI_EventCreator::get()->sendUpdated(theMoved, EVENT_UPD);
302 }
303
304 void Model_Objects::clearHistory(ObjectPtr theObj)
305 {
306   if (theObj) {
307     const std::string aGroup = theObj->groupName();
308     std::map<std::string, std::vector<ObjectPtr> >::iterator aHIter = myHistory.find(aGroup);
309     if (aHIter != myHistory.end())
310       myHistory.erase(aHIter); // erase from map => this means that it is not synchronized
311     if (theObj->groupName() == ModelAPI_Feature::group()) { // clear results group of the feature
312       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObj);
313       std::string aResultGroup = featureResultGroup(aFeature);
314       if (!aResultGroup.empty()) {
315         std::map<std::string, std::vector<ObjectPtr> >::iterator aHIter = 
316           myHistory.find(aResultGroup);
317         if (aHIter != myHistory.end())
318           myHistory.erase(aHIter); // erase from map => this means that it is not synchronized
319       }
320     }
321   }
322 }
323
324 void Model_Objects::createHistory(const std::string& theGroupID)
325 {
326   std::map<std::string, std::vector<ObjectPtr> >::iterator aHIter = myHistory.find(theGroupID);
327   if (aHIter == myHistory.end()) {
328     myHistory[theGroupID] = std::vector<ObjectPtr>();
329     std::vector<ObjectPtr>& aResult = myHistory[theGroupID];
330     // iterate the array of references and get feature by feature from the array
331     bool isFeature = theGroupID == ModelAPI_Feature::group();
332     Handle(TDataStd_ReferenceArray) aRefs;
333     if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
334       for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
335         FeaturePtr aFeature = feature(aRefs->Value(a));
336         if (aFeature.get()) {
337           // if feature is in sub-component, remove it from history: it is in sub-tree of sub-component
338           if (!ModelAPI_Tools::compositeOwner(aFeature).get()) {
339             if (isFeature) { // here may be also disabled features
340               if (aFeature->isInHistory()) {
341                 aResult.push_back(aFeature);
342               }
343             } else if (!aFeature->isDisabled()) { // iterate all results of not-disabled feature
344               const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
345               std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
346               for (; aRIter != aResults.cend(); aRIter++) {
347                 ResultPtr aRes = *aRIter;
348                 if (aRes->groupName() != theGroupID) break; // feature have only same group results
349                 if (!aRes->isDisabled() && aRes->isInHistory() && !aRes->isConcealed()) {
350                   aResult.push_back(*aRIter);
351                 }
352               }
353             }
354           }
355         }
356       }
357     }
358   }
359 }
360
361 void Model_Objects::updateHistory(const std::shared_ptr<ModelAPI_Object> theObject)
362 {
363   clearHistory(theObject);
364 }
365
366 void Model_Objects::updateHistory(const std::string theGroup)
367 {
368   std::map<std::string, std::vector<ObjectPtr> >::iterator aHIter = myHistory.find(theGroup);
369   if (aHIter != myHistory.end())
370     myHistory.erase(aHIter); // erase from map => this means that it is not synchronized
371 }
372
373 FeaturePtr Model_Objects::feature(TDF_Label theLabel) const
374 {
375   if (myFeatures.IsBound(theLabel))
376     return myFeatures.Find(theLabel);
377   return FeaturePtr();  // not found
378 }
379
380 ObjectPtr Model_Objects::object(TDF_Label theLabel)
381 {
382   // try feature by label
383   FeaturePtr aFeature = feature(theLabel);
384   if (aFeature)
385     return feature(theLabel);
386   TDF_Label aFeatureLabel = theLabel.Father().Father();  // let's suppose it is result
387   aFeature = feature(aFeatureLabel);
388   bool isSubResult = false;
389   if (!aFeature.get() && aFeatureLabel.Depth() > 1) { // let's suppose this is sub-result of result
390     aFeatureLabel = aFeatureLabel.Father().Father();
391     aFeature = feature(aFeatureLabel);
392     isSubResult = true;
393   }
394   if (aFeature) {
395     const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
396     std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.cbegin();
397     for (; aRIter != aResults.cend(); aRIter++) {
398       if (isSubResult) {
399         ResultCompSolidPtr aCompRes = std::dynamic_pointer_cast<ModelAPI_ResultCompSolid>(*aRIter);
400         if (aCompRes) {
401           int aNumSubs = aCompRes->numberOfSubs();
402           for(int a = 0; a < aNumSubs; a++) {
403             ResultPtr aSub = aCompRes->subResult(a);
404             if (aSub.get()) {
405               std::shared_ptr<Model_Data> aSubData = std::dynamic_pointer_cast<Model_Data>(
406                   aSub->data());
407               if (aSubData->label().Father().IsEqual(theLabel))
408                 return aSub;
409             }
410           }
411         }
412       } else {
413         std::shared_ptr<Model_Data> aResData = std::dynamic_pointer_cast<Model_Data>(
414             (*aRIter)->data());
415         if (aResData->label().Father().IsEqual(theLabel))
416           return *aRIter;
417       }
418     }
419   }
420   return FeaturePtr();  // not found
421 }
422
423 ObjectPtr Model_Objects::object(const std::string& theGroupID, const int theIndex)
424 {
425   if (theIndex == -1)
426     return ObjectPtr();
427   createHistory(theGroupID);
428   return myHistory[theGroupID][theIndex];
429 }
430
431 std::shared_ptr<ModelAPI_Object> Model_Objects::objectByName(
432     const std::string& theGroupID, const std::string& theName)
433 {
434   createHistory(theGroupID);
435   std::vector<ObjectPtr>& allObjs = myHistory[theGroupID];
436   std::vector<ObjectPtr>::iterator anObjIter = allObjs.begin();
437   for(; anObjIter != allObjs.end(); anObjIter++) {
438     if ((*anObjIter)->data()->name() == theName)
439       return *anObjIter;
440   }
441   // not found
442   return ObjectPtr();
443 }
444
445 const int Model_Objects::index(std::shared_ptr<ModelAPI_Object> theObject)
446 {
447   std::string aGroup = theObject->groupName();
448   createHistory(aGroup);
449   std::vector<ObjectPtr>& allObjs = myHistory[aGroup];
450   std::vector<ObjectPtr>::iterator anObjIter = allObjs.begin(); // iterate to search object
451   for(int anIndex = 0; anObjIter != allObjs.end(); anObjIter++, anIndex++) {
452     if ((*anObjIter) == theObject)
453       return anIndex;
454   }
455   // not found
456   return -1;
457 }
458
459 int Model_Objects::size(const std::string& theGroupID)
460 {
461   createHistory(theGroupID);
462   return myHistory[theGroupID].size();
463 }
464
465 void Model_Objects::allResults(const std::string& theGroupID, std::list<ResultPtr>& theResults)
466 {
467   // iterate the array of references and get feature by feature from the array
468   Handle(TDataStd_ReferenceArray) aRefs;
469   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
470     for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
471       FeaturePtr aFeature = feature(aRefs->Value(a));
472       if (aFeature.get()) {
473         const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
474         std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
475         for (; aRIter != aResults.cend(); aRIter++) {
476           ResultPtr aRes = *aRIter;
477           if (aRes->groupName() != theGroupID) break; // feature have only same group results
478           if (aRes->isInHistory() && !aRes->isConcealed()) {
479             theResults.push_back(*aRIter);
480           }
481         }
482       }
483     }
484   }
485 }
486
487
488 TDF_Label Model_Objects::featuresLabel() const
489 {
490   return myMain.FindChild(TAG_OBJECTS);
491 }
492
493 void Model_Objects::setUniqueName(FeaturePtr theFeature)
494 {
495   if (!theFeature->data()->name().empty())
496     return;  // not needed, name is already defined
497   std::string aName;  // result
498   // first count all features of such kind to start with index = count + 1
499   int aNumObjects = -1; // this feature is already in this map
500   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myFeatures);
501   for (; aFIter.More(); aFIter.Next()) {
502     if (aFIter.Value()->getKind() == theFeature->getKind())
503       aNumObjects++;
504   }
505   // generate candidate name
506   std::stringstream aNameStream;
507   aNameStream << theFeature->getKind() << "_" << aNumObjects + 1;
508   aName = aNameStream.str();
509   // check this is unique, if not, increase index by 1
510   for (aFIter.Initialize(myFeatures); aFIter.More();) {
511     FeaturePtr aFeature = aFIter.Value();
512     bool isSameName = aFeature->data()->name() == aName;
513     if (!isSameName) {  // check also results to avoid same results names (actual for Parts)
514       const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
515       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
516       for (; aRIter != aResults.cend(); aRIter++) {
517         isSameName = (*aRIter)->data()->name() == aName;
518       }
519     }
520     if (isSameName) {
521       aNumObjects++;
522       std::stringstream aNameStream;
523       aNameStream << theFeature->getKind() << "_" << aNumObjects + 1;
524       aName = aNameStream.str();
525       // reinitialize iterator to make sure a new name is unique
526       aFIter.Initialize(myFeatures);
527     } else
528       aFIter.Next();
529   }
530   theFeature->data()->setName(aName);
531 }
532
533 void Model_Objects::initData(ObjectPtr theObj, TDF_Label theLab, const int theTag)
534 {
535   std::shared_ptr<Model_Data> aData(new Model_Data);
536   aData->setLabel(theLab.FindChild(theTag));
537   aData->setObject(theObj);
538   theObj->setDoc(myDoc);
539   theObj->setData(aData);
540   FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObj);
541   if (aFeature) {
542     setUniqueName(aFeature);  // must be before "initAttributes" because duplicate part uses name
543   }
544   theObj->initAttributes();
545 }
546
547 void Model_Objects::synchronizeFeatures(
548   const TDF_LabelList& theUpdated, const bool theUpdateReferences, const bool theFlush)
549 {
550   Model_Document* anOwner = std::dynamic_pointer_cast<Model_Document>(myDoc).get();
551   if (!anOwner) // this may happen on creation of document: nothing there, so nothing to synchronize
552     return;
553   // after all updates, sends a message that groups of features were created or updated
554   Events_Loop* aLoop = Events_Loop::loop();
555   static Events_ID aDispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
556   static Events_ID aCreateEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
557   static Events_ID anUpdateEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
558   static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
559   static Events_ID aDeleteEvent = Events_Loop::eventByName(EVENT_OBJECT_DELETED);
560   static Events_ID aToHideEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
561   bool isActive = aLoop->activateFlushes(false);
562
563   // collect all updated labels map
564   TDF_LabelMap anUpdatedMap;
565   TDF_ListIteratorOfLabelList anUpdatedIter(theUpdated);
566   for(; anUpdatedIter.More(); anUpdatedIter.Next()) {
567     TDF_Label& aFeatureLab = anUpdatedIter.Value();
568     while(aFeatureLab.Depth() > 3)
569       aFeatureLab = aFeatureLab.Father();
570     if (myFeatures.IsBound(aFeatureLab))
571       anUpdatedMap.Add(aFeatureLab);
572   }
573
574   // update all objects by checking are they on labels or not
575   std::set<FeaturePtr> aNewFeatures, aKeptFeatures;
576   TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
577   for (; aLabIter.More(); aLabIter.Next()) {
578     TDF_Label aFeatureLabel = aLabIter.Value()->Label();
579     FeaturePtr aFeature;
580     if (!myFeatures.IsBound(aFeatureLabel)) {  // a new feature is inserted
581       // create a feature
582       aFeature = std::dynamic_pointer_cast<Model_Session>(ModelAPI_Session::get())->createFeature(
583         TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(aLabIter.Value())->Get())
584         .ToCString(), anOwner);
585       if (!aFeature) {  // somethig is wrong, most probably, the opened document has invalid structure
586         Events_Error::send("Invalid type of object in the document");
587         aLabIter.Value()->Label().ForgetAllAttributes();
588         continue;
589       }
590       // this must be before "setData" to redo the sketch line correctly
591       myFeatures.Bind(aFeatureLabel, aFeature);
592       aNewFeatures.insert(aFeature);
593       initData(aFeature, aFeatureLabel, TAG_FEATURE_ARGUMENTS);
594       updateHistory(aFeature);
595       aFeature->setDisabled(false); // by default created feature is enabled (this allows to recreate the results before "setCurrent" is called)
596
597       // event: model is updated
598       ModelAPI_EventCreator::get()->sendUpdated(aFeature, aCreateEvent);
599     } else {  // nothing is changed, both iterators are incremented
600       aFeature = myFeatures.Find(aFeatureLabel);
601       aKeptFeatures.insert(aFeature);
602       if (anUpdatedMap.Contains(aFeatureLabel)) {
603         ModelAPI_EventCreator::get()->sendUpdated(aFeature, anUpdateEvent);
604       }
605     }
606   }
607
608   // check all features are checked: if not => it was removed
609   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myFeatures);
610   while (aFIter.More()) {
611     if (aKeptFeatures.find(aFIter.Value()) == aKeptFeatures.end()
612       && aNewFeatures.find(aFIter.Value()) == aNewFeatures.end()) {
613         FeaturePtr aFeature = aFIter.Value();
614         // event: model is updated
615         //if (aFeature->isInHistory()) {
616         ModelAPI_EventCreator::get()->sendDeleted(myDoc, ModelAPI_Feature::group());
617         //}
618         // results of this feature must be redisplayed (hided)
619         // redisplay also removed feature (used for sketch and AISObject)
620         ModelAPI_EventCreator::get()->sendUpdated(aFeature, aRedispEvent);
621         updateHistory(aFeature);
622         aFeature->erase();
623         // unbind after the "erase" call: on abort sketch is removes sub-objects that corrupts aFIter
624         myFeatures.UnBind(aFIter.Key());
625         // reinitialize iterator because unbind may corrupt the previous order in the map
626         aFIter.Initialize(myFeatures);
627     } else
628       aFIter.Next();
629   }
630
631   if (theUpdateReferences) {
632     synchronizeBackRefs();
633   }
634   // update results of the features (after features created because they may be connected, like sketch and sub elements)
635   // After synchronisation of back references because sketch must be set in sub-elements before "execute" by updateResults
636   std::list<FeaturePtr> aComposites; // composites must be updated after their subs (issue 360)
637   TDF_ChildIDIterator aLabIter2(featuresLabel(), TDataStd_Comment::GetID());
638   for (; aLabIter2.More(); aLabIter2.Next()) {
639     TDF_Label aFeatureLabel = aLabIter2.Value()->Label();
640     if (myFeatures.IsBound(aFeatureLabel)) {  // a new feature is inserted
641       FeaturePtr aFeature = myFeatures.Find(aFeatureLabel);
642       if (std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aFeature).get())
643         aComposites.push_back(aFeature);
644       updateResults(aFeature);
645     }
646   }
647   std::list<FeaturePtr>::iterator aComposite = aComposites.begin();
648   for(; aComposite != aComposites.end(); aComposite++) {
649     updateResults(*aComposite);
650   }
651
652   // the synchronize should be done after updateResults in order to correct back references of updated results
653   if (theUpdateReferences) {
654     synchronizeBackRefs();
655   }
656   if (!theUpdated.IsEmpty()) { // this means there is no control what was modified => remove history cash
657     myHistory.clear();
658   }
659
660   anOwner->executeFeatures() = false;
661   aLoop->activateFlushes(isActive);
662
663   if (theFlush) {
664     aLoop->flush(aCreateEvent);
665     aLoop->flush(aDeleteEvent);
666     aLoop->flush(anUpdateEvent);
667     aLoop->flush(aRedispEvent);
668     aLoop->flush(aToHideEvent);
669   }
670   anOwner->executeFeatures() = true;
671 }
672
673 void Model_Objects::synchronizeBackRefs()
674 {
675   // keeps the concealed flags of result to catch the change and create created/deleted events
676   std::list<std::pair<ResultPtr, bool> > aConcealed;
677   // first cycle: erase all data about back-references
678   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFeatures(myFeatures);
679   for(; aFeatures.More(); aFeatures.Next()) {
680     FeaturePtr aFeature = aFeatures.Value();
681     std::shared_ptr<Model_Data> aFData = 
682       std::dynamic_pointer_cast<Model_Data>(aFeature->data());
683     if (aFData) {
684       aFData->eraseBackReferences();
685     }
686     const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
687     std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
688     for (; aRIter != aResults.cend(); aRIter++) {
689       std::shared_ptr<Model_Data> aResData = 
690         std::dynamic_pointer_cast<Model_Data>((*aRIter)->data());
691       if (aResData) {
692         aConcealed.push_back(std::pair<ResultPtr, bool>(*aRIter, (*aRIter)->isConcealed()));
693         aResData->eraseBackReferences();
694       }
695     }
696   }
697
698   // second cycle: set new back-references: only features may have reference, iterate only them
699   ModelAPI_ValidatorsFactory* aValidators = ModelAPI_Session::get()->validators();
700   for(aFeatures.Initialize(myFeatures); aFeatures.More(); aFeatures.Next()) {
701     FeaturePtr aFeature = aFeatures.Value();
702     std::shared_ptr<Model_Data> aFData = 
703       std::dynamic_pointer_cast<Model_Data>(aFeature->data());
704     if (aFData) {
705       std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
706       aFData->referencesToObjects(aRefs);
707       std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator 
708         aRefsIter = aRefs.begin();
709       for(; aRefsIter != aRefs.end(); aRefsIter++) {
710         std::list<ObjectPtr>::iterator aRefTo = aRefsIter->second.begin();
711         for(; aRefTo != aRefsIter->second.end(); aRefTo++) {
712           if (*aRefTo) {
713             std::shared_ptr<Model_Data> aRefData = 
714               std::dynamic_pointer_cast<Model_Data>((*aRefTo)->data());
715             aRefData->addBackReference(aFeature, aRefsIter->first); // here the Concealed flag is updated
716             // update enable/disable status: the nested status must be equal to the composite
717             CompositeFeaturePtr aComp = 
718               std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(aFeature);
719             if (aComp.get()) {
720               FeaturePtr aReferenced = std::dynamic_pointer_cast<ModelAPI_Feature>(*aRefTo);
721               if (aReferenced.get()) {
722                 aReferenced->setDisabled(aComp->isDisabled());
723               }
724             }
725           }
726         }
727       }
728     }
729   }
730   std::list<std::pair<ResultPtr, bool> >::iterator aCIter = aConcealed.begin();
731   for(; aCIter != aConcealed.end(); aCIter++) {
732     if (aCIter->first->isConcealed() != aCIter->second) { // somethign is changed => produce event
733       if (aCIter->second) { // was concealed become not => creation event
734         static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
735         ModelAPI_EventCreator::get()->sendUpdated(aCIter->first, anEvent);
736       } else { // was not concealed become concealed => delete event
737         ModelAPI_EventCreator::get()->sendDeleted(myDoc, aCIter->first->groupName());
738         // redisplay for the viewer (it must be disappeared also)
739         static Events_ID EVENT_DISP = 
740           Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
741         ModelAPI_EventCreator::get()->sendUpdated(aCIter->first, EVENT_DISP);
742       }
743     }
744   }
745 }
746
747 TDF_Label Model_Objects::resultLabel(
748   const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theResultIndex) 
749 {
750   const std::shared_ptr<Model_Data>& aData = 
751     std::dynamic_pointer_cast<Model_Data>(theFeatureData);
752   return aData->label().Father().FindChild(TAG_FEATURE_RESULTS).FindChild(theResultIndex + 1);
753 }
754
755 void Model_Objects::storeResult(std::shared_ptr<ModelAPI_Data> theFeatureData,
756                                  std::shared_ptr<ModelAPI_Result> theResult,
757                                  const int theResultIndex)
758 {
759   theResult->setDoc(myDoc);
760   initData(theResult, resultLabel(theFeatureData, theResultIndex), TAG_FEATURE_ARGUMENTS);
761   if (theResult->data()->name().empty()) {  // if was not initialized, generate event and set a name
762     std::stringstream aNewName;
763     aNewName<<theFeatureData->name();
764     if (theResultIndex > 0) // if there are several results, add unique prefix starting from second
765       aNewName<<"_"<<theResultIndex + 1;
766     theResult->data()->setName(aNewName.str());
767   }
768 }
769
770 std::shared_ptr<ModelAPI_ResultConstruction> Model_Objects::createConstruction(
771     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
772 {
773   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
774   TDataStd_Comment::Set(aLab, ModelAPI_ResultConstruction::group().c_str());
775   ObjectPtr anOldObject = object(aLab);
776   std::shared_ptr<ModelAPI_ResultConstruction> aResult;
777   if (anOldObject) {
778     aResult = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(anOldObject);
779   }
780   if (!aResult) {
781     aResult = std::shared_ptr<ModelAPI_ResultConstruction>(new Model_ResultConstruction);
782     storeResult(theFeatureData, aResult, theIndex);
783   }
784   return aResult;
785 }
786
787 std::shared_ptr<ModelAPI_ResultBody> Model_Objects::createBody(
788     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
789 {
790   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
791   // for feature create compsolid, but for result sub create body: 
792   // only one level of recursion is supported now
793   ResultPtr aResultOwner = std::dynamic_pointer_cast<ModelAPI_Result>(theFeatureData->owner());
794   ObjectPtr anOldObject;
795   if (aResultOwner.get()) {
796     TDataStd_Comment::Set(aLab, ModelAPI_ResultBody::group().c_str());
797   } else { // in compsolid (higher level result) old object probably may be found
798     TDataStd_Comment::Set(aLab, ModelAPI_ResultCompSolid::group().c_str());
799     anOldObject = object(aLab);
800   }
801   std::shared_ptr<ModelAPI_ResultBody> aResult;
802   if (anOldObject) {
803     aResult = std::dynamic_pointer_cast<ModelAPI_ResultBody>(anOldObject);
804   }
805   if (!aResult) {
806     // create compsolid anyway; if it is compsolid, it will create sub-bodies internally
807     if (aResultOwner.get()) {
808       aResult = std::shared_ptr<ModelAPI_ResultBody>(new Model_ResultBody);
809     } else {
810       aResult = std::shared_ptr<ModelAPI_ResultBody>(new Model_ResultCompSolid);
811     }
812     storeResult(theFeatureData, aResult, theIndex);
813   }
814   return aResult;
815 }
816
817 std::shared_ptr<ModelAPI_ResultPart> Model_Objects::createPart(
818     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
819 {
820   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
821   TDataStd_Comment::Set(aLab, ModelAPI_ResultPart::group().c_str());
822   ObjectPtr anOldObject = object(aLab);
823   std::shared_ptr<ModelAPI_ResultPart> aResult;
824   if (anOldObject) {
825     aResult = std::dynamic_pointer_cast<ModelAPI_ResultPart>(anOldObject);
826   }
827   if (!aResult) {
828     aResult = std::shared_ptr<ModelAPI_ResultPart>(new Model_ResultPart);
829     storeResult(theFeatureData, aResult, theIndex);
830   }
831   return aResult;
832 }
833
834 std::shared_ptr<ModelAPI_ResultPart> Model_Objects::copyPart(
835     const std::shared_ptr<ModelAPI_ResultPart>& theOrigin,
836     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
837 {
838   std::shared_ptr<ModelAPI_ResultPart> aResult = createPart(theFeatureData, theIndex);
839   aResult->data()->reference(Model_ResultPart::BASE_REF_ID())->setValue(theOrigin);
840   return aResult;
841 }
842
843 std::shared_ptr<ModelAPI_ResultGroup> Model_Objects::createGroup(
844     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
845 {
846   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
847   TDataStd_Comment::Set(aLab, ModelAPI_ResultGroup::group().c_str());
848   ObjectPtr anOldObject = object(aLab);
849   std::shared_ptr<ModelAPI_ResultGroup> aResult;
850   if (anOldObject) {
851     aResult = std::dynamic_pointer_cast<ModelAPI_ResultGroup>(anOldObject);
852   }
853   if (!aResult) {
854     aResult = std::shared_ptr<ModelAPI_ResultGroup>(new Model_ResultGroup(theFeatureData));
855     storeResult(theFeatureData, aResult, theIndex);
856   }
857   return aResult;
858 }
859
860 std::shared_ptr<ModelAPI_ResultParameter> Model_Objects::createParameter(
861       const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
862 {
863   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
864   TDataStd_Comment::Set(aLab, ModelAPI_ResultParameter::group().c_str());
865   ObjectPtr anOldObject = object(aLab);
866   std::shared_ptr<ModelAPI_ResultParameter> aResult;
867   if (anOldObject) {
868     aResult = std::dynamic_pointer_cast<ModelAPI_ResultParameter>(anOldObject);
869   }
870   if (!aResult) {
871     aResult = std::shared_ptr<ModelAPI_ResultParameter>(new Model_ResultParameter);
872     storeResult(theFeatureData, aResult, theIndex);
873   }
874   return aResult;
875 }
876
877 std::shared_ptr<ModelAPI_Feature> Model_Objects::feature(
878     const std::shared_ptr<ModelAPI_Result>& theResult)
879 {
880   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(theResult->data());
881   if (aData) {
882     TDF_Label aFeatureLab = aData->label().Father().Father().Father();
883     FeaturePtr aFeature = feature(aFeatureLab);
884     if (!aFeature.get() && aFeatureLab.Depth() > 1) { // this may be sub-result of result
885       aFeatureLab = aFeatureLab.Father().Father();
886       aFeature = feature(aFeatureLab);
887     }
888     return aFeature;
889   }
890   return FeaturePtr();
891 }
892
893 std::string Model_Objects::featureResultGroup(FeaturePtr theFeature)
894 {
895   if (theFeature->data()->isValid()) {
896     TDF_ChildIterator aLabIter(resultLabel(theFeature->data(), 0).Father());
897     if (aLabIter.More()) {
898       TDF_Label anArgLab = aLabIter.Value();
899       Handle(TDataStd_Comment) aGroup;
900       if (aLabIter.Value().FindAttribute(TDataStd_Comment::GetID(), aGroup)) {
901         return TCollection_AsciiString(aGroup->Get()).ToCString();
902       }
903     }
904   }
905   static std::string anEmpty;
906   return anEmpty; // not found
907 }
908
909 void Model_Objects::updateResults(FeaturePtr theFeature)
910 {
911   // for not persistent is will be done by parametric updater automatically
912   //if (!theFeature->isPersistentResult()) return;
913   // check the existing results and remove them if there is nothing on the label
914   std::list<ResultPtr>::const_iterator aResIter = theFeature->results().cbegin();
915   while(aResIter != theFeature->results().cend()) {
916     ResultPtr aBody = std::dynamic_pointer_cast<ModelAPI_Result>(*aResIter);
917     if (aBody.get()) {
918       if (!aBody->data()->isValid()) { 
919         // found a disappeared result => remove it
920         theFeature->eraseResultFromList(aBody);
921         // start iterate from beginning because iterator is corrupted by removing
922         aResIter = theFeature->results().cbegin();
923         continue;
924       }
925     }
926     aResIter++;
927   }
928   // it may be on undo
929   if (!theFeature->data() || !theFeature->data()->isValid() || theFeature->isDisabled())
930     return;
931   // check that results are presented on all labels
932   int aResSize = theFeature->results().size();
933   TDF_ChildIterator aLabIter(resultLabel(theFeature->data(), 0).Father());
934   for(; aLabIter.More(); aLabIter.Next()) {
935     // here must be GUID of the feature
936     int aResIndex = aLabIter.Value().Tag() - 1;
937     ResultPtr aNewBody;
938     if (aResSize <= aResIndex) {
939       TDF_Label anArgLab = aLabIter.Value();
940       Handle(TDataStd_Comment) aGroup;
941       if (anArgLab.FindAttribute(TDataStd_Comment::GetID(), aGroup)) {
942         if (aGroup->Get() == ModelAPI_ResultBody::group().c_str() || 
943             aGroup->Get() == ModelAPI_ResultCompSolid::group().c_str()) {
944           aNewBody = createBody(theFeature->data(), aResIndex);
945         } else if (aGroup->Get() == ModelAPI_ResultPart::group().c_str()) {
946           std::shared_ptr<ModelAPI_ResultPart> aNewP = createPart(theFeature->data(), aResIndex); 
947           theFeature->setResult(aNewP, aResIndex);
948           if (!aNewP->partDoc().get())
949             theFeature->execute(); // create the part result: it is better to restore the previous result if it is possible
950           break;
951         } else if (aGroup->Get() == ModelAPI_ResultConstruction::group().c_str()) {
952           theFeature->execute(); // construction shapes are needed for sketch solver
953           break;
954         } else if (aGroup->Get() == ModelAPI_ResultGroup::group().c_str()) {
955           aNewBody = createGroup(theFeature->data(), aResIndex);
956         } else if (aGroup->Get() == ModelAPI_ResultParameter::group().c_str()) {
957           theFeature->attributeChanged("expression"); // just produce a value
958           break;
959         } else {
960           Events_Error::send(std::string("Unknown type of result is found in the document:") +
961             TCollection_AsciiString(aGroup->Get()).ToCString());
962         }
963       }
964       if (aNewBody) {
965         theFeature->setResult(aNewBody, aResIndex);
966       }
967     }
968   }
969 }
970
971 ResultPtr Model_Objects::findByName(const std::string theName)
972 {
973   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator anObjIter(myFeatures);
974   for(; anObjIter.More(); anObjIter.Next()) {
975     FeaturePtr& aFeature = anObjIter.ChangeValue();
976     if (!aFeature.get() || aFeature->isDisabled()) // may be on close
977       continue;
978     const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
979     std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
980     for (; aRIter != aResults.cend(); aRIter++) {
981       ResultPtr aRes = *aRIter;
982       if (aRes.get() && aRes->data() && aRes->data()->isValid() && !aRes->isDisabled() &&
983           aRes->data()->name() == theName) {
984         return aRes;
985       }
986     }
987   }
988   // not found
989   return ResultPtr();
990 }
991
992 FeaturePtr Model_Objects::nextFeature(FeaturePtr theCurrent, const bool theReverse)
993 {
994   std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theCurrent->data());
995   if (aData && aData->isValid()) {
996     TDF_Label aFeatureLabel = aData->label().Father();
997     Handle(TDataStd_ReferenceArray) aRefs;
998     if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
999       for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) { // iterate all existing features
1000         if (aRefs->Value(a).IsEqual(aFeatureLabel)) {
1001           a += theReverse ? -1 : 1;
1002           if (a >= aRefs->Lower() && a <= aRefs->Upper())
1003             return feature(aRefs->Value(a));
1004           break; // finish iiteration: it's last feature
1005         }
1006       }
1007     }
1008   }
1009   return FeaturePtr(); // not found, last, or something is wrong
1010 }
1011
1012 FeaturePtr Model_Objects::firstFeature()
1013 {
1014   Handle(TDataStd_ReferenceArray) aRefs;
1015   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
1016     return feature(aRefs->Value(aRefs->Lower()));
1017   }
1018   return FeaturePtr(); // no features at all
1019 }
1020
1021 FeaturePtr Model_Objects::lastFeature()
1022 {
1023   Handle(TDataStd_ReferenceArray) aRefs;
1024   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
1025     return feature(aRefs->Value(aRefs->Upper()));
1026   }
1027   return FeaturePtr(); // no features at all
1028 }
1029
1030 std::list<std::shared_ptr<ModelAPI_Feature> > Model_Objects::allFeatures()
1031 {
1032   std::list<std::shared_ptr<ModelAPI_Feature> > aResult;
1033   Handle(TDataStd_ReferenceArray) aRefs;
1034   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
1035     for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
1036       FeaturePtr aFeature = feature(aRefs->Value(a));
1037       if (aFeature.get())
1038         aResult.push_back(aFeature);
1039     }
1040   }
1041   return aResult;
1042 }
1043
1044 int Model_Objects::numInternalFeatures()
1045 {
1046   Handle(TDataStd_ReferenceArray) aRefs;
1047   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
1048     return aRefs->Upper() - aRefs->Lower() + 1;
1049   }
1050   return 0; // invalid
1051 }
1052
1053 std::shared_ptr<ModelAPI_Feature> Model_Objects::internalFeature(const int theIndex)
1054 {
1055   Handle(TDataStd_ReferenceArray) aRefs;
1056   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
1057     return feature(aRefs->Value(aRefs->Lower() + theIndex));
1058   }
1059   return FeaturePtr(); // invalid
1060 }
1061
1062 Standard_Integer HashCode(const TDF_Label& theLab, const Standard_Integer theUpper)
1063 {
1064   return TDF_LabelMapHasher::HashCode(theLab, theUpper);
1065
1066 }
1067 Standard_Boolean IsEqual(const TDF_Label& theLab1, const TDF_Label& theLab2)
1068 {
1069   return TDF_LabelMapHasher::IsEqual(theLab1, theLab2);
1070 }