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