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