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