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