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