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