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