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