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