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