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