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