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