]> SALOME platform Git repositories - modules/shaper.git/blob - src/Model/Model_Objects.cpp
Salome HOME
[GITHUB #2] problem in export dialog - difference in STEP vs BREP
[modules/shaper.git] / src / Model / Model_Objects.cpp
1 // Copyright (C) 2014-2024  CEA, EDF
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 #include <Model_Objects.h>
21
22 #include <Basics_OCCTVersion.hxx>
23
24 #include <Model_Data.h>
25 #include <Model_Document.h>
26 #include <Model_Events.h>
27 #include <Model_Session.h>
28 #include <Model_ResultPart.h>
29 #include <Model_ResultConstruction.h>
30 #include <Model_ResultBody.h>
31 #include <Model_ResultGroup.h>
32 #include <Model_ResultField.h>
33 #include <Model_ResultParameter.h>
34 #include <Model_AttributeRefList.h>
35 #include <ModelAPI_Validator.h>
36 #include <ModelAPI_CompositeFeature.h>
37 #include <ModelAPI_Tools.h>
38 #include <ModelAPI_Filter.h>
39
40
41 #include <Events_Loop.h>
42 #include <Events_InfoMessage.h>
43
44 #include <Locale_Convert.h>
45
46 #include <TDataStd_Integer.hxx>
47 #include <TDataStd_Comment.hxx>
48 #include <TDF_ChildIDIterator.hxx>
49 #include <TDataStd_ReferenceArray.hxx>
50 #include <TDataStd_HLabelArray1.hxx>
51 #include <TDF_Reference.hxx>
52 #include <TDF_ChildIDIterator.hxx>
53 #include <TDF_LabelMap.hxx>
54 #include <TDF_ListIteratorOfLabelList.hxx>
55
56 #if OCC_VERSION_LARGE < 0x07080000
57
58 #include <TDF_LabelMapHasher.hxx>
59 // for TDF_Label map usage
60 static Standard_Integer HashCode(const TDF_Label& theLab, const Standard_Integer theUpper);
61 static Standard_Boolean IsEqual(const TDF_Label& theLab1, const TDF_Label& theLab2);
62
63 #endif
64
65 int kUNDEFINED_FEATURE_INDEX = -1;
66
67 static const std::string& groupNameFoldering(const std::string& theGroupID,
68                                              const bool theAllowFolder)
69 {
70   if (theAllowFolder) {
71     static const std::string anOutOfFolderName = std::string("__") + ModelAPI_Feature::group();
72     static const std::string aDummyName;
73     return theGroupID == ModelAPI_Feature::group() ? anOutOfFolderName : aDummyName;
74   }
75   return theGroupID;
76 }
77
78 // Check theFeature is a first or last feature in folder and return this folder
79 static FolderPtr inFolder(const FeaturePtr& theFeature, const std::string& theFolderAttr)
80 {
81   const std::set<AttributePtr>& aRefs = theFeature->data()->refsToMe();
82   for (std::set<AttributePtr>::iterator anIt = aRefs.begin(); anIt != aRefs.end(); ++anIt) {
83     if ((*anIt)->id() != theFolderAttr)
84       continue;
85
86     ObjectPtr anOwner = (*anIt)->owner();
87     FolderPtr aFolder = std::dynamic_pointer_cast<ModelAPI_Folder>(anOwner);
88     if (aFolder.get())
89       return aFolder;
90   }
91   return FolderPtr();
92 }
93
94
95 static const int TAG_OBJECTS = 2;  // tag of the objects sub-tree (features, results)
96
97 // feature sub-labels
98 static const int TAG_FEATURE_ARGUMENTS = 1;  ///< where the arguments are located
99 static const int TAG_FEATURE_RESULTS = 2;  ///< where the results are located
100
101 ///
102 /// 0:1:2 - where features are located
103 /// 0:1:2:N:1 - data of the feature N
104 /// 0:1:2:N:2:K:1 - data of the K result of the feature N
105
106 Model_Objects::Model_Objects(TDF_Label theMainLab) : myMain(theMainLab)
107 {
108 }
109
110 void Model_Objects::setOwner(DocumentPtr theDoc)
111 {
112   myDoc = theDoc;
113   // update all fields and recreate features and result objects if needed
114   TDF_LabelList aNoUpdated;
115   synchronizeFeatures(aNoUpdated, true, false, true, true);
116   myHistory.clear();
117 }
118
119 Model_Objects::~Model_Objects()
120 {
121   // delete all features of this document
122   Events_Loop* aLoop = Events_Loop::loop();
123   // erase one by one to avoid access from the feature destructor itself from he map
124   // blocks the flush signals to avoid the temporary objects visualization in the viewer
125   // they should not be shown in order to do not lose highlight by erasing them
126   bool isActive = aLoop->activateFlushes(false);
127
128   while(!myFeatures.IsEmpty()) {
129     NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFeaturesIter(myFeatures);
130     FeaturePtr aFeature = aFeaturesIter.Value();
131     static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
132     ModelAPI_EventCreator::get()->sendDeleted(myDoc, ModelAPI_Feature::group());
133     ModelAPI_EventCreator::get()->sendUpdated(aFeature, EVENT_DISP);
134     aFeature->removeResults(0, false);
135     aFeature->erase();
136     myFeatures.UnBind(aFeaturesIter.Key());
137   }
138   while (!myFolders.IsEmpty()) {
139     NCollection_DataMap<TDF_Label, ObjectPtr>::Iterator aFoldersIter(myFolders);
140     ObjectPtr aFolder = aFoldersIter.Value();
141     static Events_ID EVENT_DISP = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
142     ModelAPI_EventCreator::get()->sendDeleted(myDoc, ModelAPI_Folder::group());
143     ModelAPI_EventCreator::get()->sendUpdated(aFolder, EVENT_DISP);
144     aFolder->erase();
145     myFolders.UnBind(aFoldersIter.Key());
146   }
147   myHistory.clear();
148   aLoop->activateFlushes(isActive);
149   // erase update, because features are destroyed and update should not performed for them anywhere
150   aLoop->eraseMessages(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
151   aLoop->eraseMessages(Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
152   // deleted and redisplayed is correctly performed: they know that features are destroyed
153   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
154   aLoop->flush(Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY));
155
156 }
157
158 /// Appends to the array of references a new referenced label
159 static void AddToRefArray(TDF_Label& theArrayLab, TDF_Label& theReferenced, TDF_Label& thePrevLab)
160 {
161   Handle(TDataStd_ReferenceArray) aRefs;
162   if (!theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
163     aRefs = TDataStd_ReferenceArray::Set(theArrayLab, 0, 0);
164     aRefs->SetValue(0, theReferenced);
165   } else {  // extend array by one more element
166     Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
167                                                                         aRefs->Upper() + 1);
168     int aPassedPrev = 0; // previous feature is found and passed
169     if (thePrevLab.IsNull()) { // null means that inserted feature must be the first
170       aNewArray->SetValue(aRefs->Lower(), theReferenced);
171       aPassedPrev = 1;
172     }
173     for (int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
174       aNewArray->SetValue(a + aPassedPrev, aRefs->Value(a));
175       if (!aPassedPrev && aRefs->Value(a).IsEqual(thePrevLab)) {
176         aPassedPrev = 1;
177         aNewArray->SetValue(a + 1, theReferenced);
178       }
179     }
180     if (!aPassedPrev) // not found: unknown situation
181       aNewArray->SetValue(aRefs->Upper() + 1, theReferenced);
182     aRefs->SetInternalArray(aNewArray);
183   }
184 }
185
186 void Model_Objects::addFeature(FeaturePtr theFeature, const FeaturePtr theAfterThis)
187 {
188   if (!theFeature->isAction()) {  // do not add action to the data model
189     TDF_Label aFeaturesLab = featuresLabel();
190     TDF_Label aFeatureLab = aFeaturesLab.NewChild();
191     // store feature in the features array: before "initData" because in macro features
192     // in initData it creates new features, appeared later than this
193     TDF_Label aPrevFeateureLab;
194     FolderPtr aParentFolder;
195     if (theAfterThis.get()) { // searching for the previous feature label
196       std::shared_ptr<Model_Data> aPrevData =
197         std::dynamic_pointer_cast<Model_Data>(theAfterThis->data());
198       if (aPrevData.get()) {
199         aPrevFeateureLab = aPrevData->label().Father();
200       }
201       // Check if the previous feature is the last feature in a folder,
202       // then the folder should be updated to contain additional feature.
203       // Macro features are not stored in folder.
204       if (!theFeature->isMacro()) {
205         // If the last feature is a sub-feature of composite, use parent feature
206         // to check belonging to a folder.
207         FeaturePtr afterThis = ModelAPI_Tools::compositeOwner(theAfterThis);
208         if (!afterThis)
209           afterThis = theAfterThis;
210         aParentFolder = inFolder(afterThis, ModelAPI_Folder::LAST_FEATURE_ID());
211       }
212     }
213     AddToRefArray(aFeaturesLab, aFeatureLab, aPrevFeateureLab);
214
215     // keep the feature ID to restore document later correctly
216     TDataStd_Comment::Set(aFeatureLab, theFeature->getKind().c_str());
217     myFeatures.Bind(aFeatureLab, theFeature);
218     // must be before the event sending: for OB the feature is already added
219     updateHistory(ModelAPI_Feature::group());
220     // do not change the order:
221     // initData()
222     // sendUpdated()
223     // during python script with fillet constraint feature data should be
224     // initialized before using it in GUI
225
226     // must be after binding to the map because of "Box" macro feature that
227     // creates other features in "initData"
228     initData(theFeature, aFeatureLab, TAG_FEATURE_ARGUMENTS);
229     // put feature to the end of folder if it is added while
230     // the history line is set to the last feature from the folder
231     if (aParentFolder) {
232       aParentFolder->reference(ModelAPI_Folder::LAST_FEATURE_ID())->setValue(theFeature);
233       updateHistory(ModelAPI_Folder::group());
234     }
235     // event: feature is added, mist be before "initData" to update OB correctly on Duplicate:
236     // first new part, then the content
237     static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
238     ModelAPI_EventCreator::get()->sendUpdated(theFeature, anEvent);
239   } else { // make feature has not-null data anyway
240     theFeature->setData(Model_Data::invalidData());
241     theFeature->setDoc(myDoc);
242   }
243 }
244
245 /// Appends to the array of references a new referenced label.
246 /// If theIndex is not -1, removes element at this index, not theReferenced.
247 /// \returns the index of removed element
248 static int RemoveFromRefArray(TDF_Label theArrayLab, TDF_Label theReferenced,
249   const int theIndex = -1)
250 {
251   int aResult = -1;  // no returned
252   Handle(TDataStd_ReferenceArray) aRefs;
253   if (theArrayLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
254     if (aRefs->Length() == 1) {  // just erase an array
255       if ((theIndex == -1 && aRefs->Value(0) == theReferenced) || theIndex == 0) {
256         theArrayLab.ForgetAttribute(TDataStd_ReferenceArray::GetID());
257       }
258       aResult = 0;
259     } else {  // reduce the array
260       Handle(TDataStd_HLabelArray1) aNewArray = new TDataStd_HLabelArray1(aRefs->Lower(),
261                                                                           aRefs->Upper() - 1);
262       int aCount = aRefs->Lower();
263       for (int a = aCount; a <= aRefs->Upper(); a++, aCount++) {
264         if ((theIndex == -1 && aRefs->Value(a) == theReferenced) || theIndex == a) {
265           aCount--;
266           aResult = a;
267         } else {
268           aNewArray->SetValue(aCount, aRefs->Value(a));
269         }
270       }
271       aRefs->SetInternalArray(aNewArray);
272     }
273   }
274   return aResult;
275 }
276
277 void Model_Objects::refsToFeature(FeaturePtr theFeature,
278   std::set<std::shared_ptr<ModelAPI_Feature> >& theRefs, const bool isSendError)
279 {
280   // check the feature: it must have no depended objects on it
281   // the dependencies can be in the feature results
282   std::list<ResultPtr> aResults;
283   ModelAPI_Tools::allResults(theFeature, aResults);
284   std::list<ResultPtr>::const_iterator aResIter = aResults.cbegin();
285   for (; aResIter != aResults.cend(); aResIter++) {
286     ResultPtr aResult = (*aResIter);
287     std::shared_ptr<Model_Data> aData =
288         std::dynamic_pointer_cast<Model_Data>(aResult->data());
289     if (aData.get() != NULL) {
290       const std::set<AttributePtr>& aRefs = aData->refsToMe();
291       std::set<AttributePtr>::const_iterator aRefIt = aRefs.begin(), aRefLast = aRefs.end();
292       for (; aRefIt != aRefLast; aRefIt++) {
293         FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRefIt)->owner());
294         if (aFeature.get() != NULL)
295           theRefs.insert(aFeature);
296       }
297     }
298   }
299   // the dependencies can be in the feature itself
300   std::shared_ptr<Model_Data> aData =
301       std::dynamic_pointer_cast<Model_Data>(theFeature->data());
302   if (aData.get() && !aData->refsToMe().empty()) {
303     const std::set<AttributePtr>& aRefs = aData->refsToMe();
304     std::set<AttributePtr>::const_iterator aRefIt = aRefs.begin(), aRefLast = aRefs.end();
305     for (; aRefIt != aRefLast; aRefIt++) {
306       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>((*aRefIt)->owner());
307       if (aFeature.get() != NULL)
308         theRefs.insert(aFeature);
309     }
310   }
311
312   if (!theRefs.empty() && isSendError) {
313     Events_InfoMessage("Model_Objects",
314       "Feature '%1' is used and can not be deleted").arg(theFeature->data()->name()).send();
315   }
316 }
317
318 void Model_Objects::removeFeature(FeaturePtr theFeature)
319 {
320   std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theFeature->data());
321   if (aData.get() && aData->isValid()) {
322     // checking that the sub-element of composite feature is removed: if yes, inform the owner
323     std::set<std::shared_ptr<ModelAPI_Feature> > aRefs;
324     refsToFeature(theFeature, aRefs, false);
325     std::set<std::shared_ptr<ModelAPI_Feature> >::iterator aRefIter = aRefs.begin();
326     for(; aRefIter != aRefs.end(); aRefIter++) {
327       std::shared_ptr<ModelAPI_CompositeFeature> aComposite =
328         std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(*aRefIter);
329       if (aComposite.get() && aComposite->data()->isValid() && aComposite->isSub(theFeature)) {
330         aComposite->removeFeature(theFeature);
331       }
332     }
333     // remove feature from folder
334     removeFromFolder(std::list<FeaturePtr>(1, theFeature));
335     // this must be before erase since theFeature erasing removes all information about
336     // the feature results and groups of results
337     // To reproduce: create sketch, extrusion, remove sketch => constructions tree is not updated
338     clearHistory(theFeature);
339     // erase fields
340     theFeature->erase();
341
342     TDF_Label aFeatureLabel = aData->label().Father();
343     if (myFeatures.IsBound(aFeatureLabel))
344       myFeatures.UnBind(aFeatureLabel);
345
346     static Events_ID EVENT_DISP = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
347     ModelAPI_EventCreator::get()->sendUpdated(theFeature, EVENT_DISP);
348     // erase all attributes under the label of feature
349     aFeatureLabel.ForgetAllAttributes();
350     // remove it from the references array
351     RemoveFromRefArray(featuresLabel(), aFeatureLabel);
352     // event: feature is deleted
353     ModelAPI_EventCreator::get()->sendDeleted(theFeature->document(), ModelAPI_Feature::group());
354     updateHistory(ModelAPI_Feature::group());
355   }
356 }
357
358 void Model_Objects::eraseAllFeatures()
359 {
360   static Events_ID kDispEvent = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
361   static const ModelAPI_EventCreator* kCreator = ModelAPI_EventCreator::get();
362   // make all features invalid (like deleted)
363   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myFeatures);
364   for(; aFIter.More(); aFIter.Next()) {
365     FeaturePtr aFeature = aFIter.Value();
366     std::list<ResultPtr> aResList;
367     ModelAPI_Tools::allResults(aFeature, aResList);
368     std::list<ResultPtr>::iterator aRIter = aResList.begin();
369     for(; aRIter != aResList.end(); aRIter++) {
370       ResultPtr aRes = *aRIter;
371       if (aRes && aRes->data()->isValid()) {
372         kCreator->sendDeleted(myDoc, aRes->groupName());
373         kCreator->sendUpdated(aRes, kDispEvent);
374         aRes->setData(aRes->data()->invalidPtr());
375
376       }
377     }
378     kCreator->sendUpdated(aFeature, kDispEvent);
379     aFeature->setData(aFeature->data()->invalidPtr());
380   }
381   kCreator->sendDeleted(myDoc, ModelAPI_Feature::group());
382   myFeatures.Clear(); // just remove features without modification of DS
383   myHistory.clear();
384 }
385
386 void Model_Objects::moveFeature(FeaturePtr theMoved, FeaturePtr theAfterThis)
387 {
388   TDF_Label aFeaturesLab = featuresLabel();
389   Handle(TDataStd_ReferenceArray) aRefs;
390   if (!aFeaturesLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
391     return;
392   TDF_Label anAfterLab, aMovedLab =
393     std::dynamic_pointer_cast<Model_Data>(theMoved->data())->label().Father();
394   if (theAfterThis.get())
395     anAfterLab = std::dynamic_pointer_cast<Model_Data>(theAfterThis->data())->label().Father();
396
397   // check whether some folder refers to the moved feature by start or end: if yes, remove from it
398   removeFromFolder(std::list<FeaturePtr>(1, theMoved));
399
400   Handle(TDataStd_HLabelArray1) aNewArray =
401     new TDataStd_HLabelArray1(aRefs->Lower(), aRefs->Upper());
402   int aPassedMovedFrom = 0; // the previous feature location is found and passed
403   int aPassedMovedTo = 0; // the feature is added and this location is passed
404   if (!theAfterThis.get()) { // null means that inserted feature must be the first
405     aNewArray->SetValue(aRefs->Lower(), aMovedLab);
406     aPassedMovedTo = 1;
407   }
408   for (int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
409     if (aPassedMovedTo == 0 && aRefs->Value(a) == anAfterLab) { // add two
410       aPassedMovedTo++;
411       aNewArray->SetValue(a - aPassedMovedFrom, anAfterLab);
412       if (a + 1 - aPassedMovedFrom <= aRefs->Upper())
413         aNewArray->SetValue(a + 1 - aPassedMovedFrom, aMovedLab);
414     } else if (aPassedMovedFrom == 0 && aRefs->Value(a) == aMovedLab) { // skip
415       aPassedMovedFrom++;
416     } else { // just copy one
417       if (a - aPassedMovedFrom + aPassedMovedTo <= aRefs->Upper())
418         aNewArray->SetValue(a - aPassedMovedFrom + aPassedMovedTo, aRefs->Value(a));
419     }
420   }
421   if (!aPassedMovedFrom || !aPassedMovedTo) {// not found: unknown situation
422     if (!aPassedMovedFrom) {
423       static std::string aMovedFromError("The moved feature is not found");
424       Events_InfoMessage("Model_Objects", aMovedFromError).send();
425     } else {
426       static std::string aMovedToError("The 'after' feature for movement is not found");
427       Events_InfoMessage("Model_Objects", aMovedToError).send();
428     }
429     return;
430   }
431   // store the new array
432   aRefs->SetInternalArray(aNewArray);
433   // update the feature and the history
434   clearHistory(theMoved);
435   // make sure all (selection) attributes of moved feature will be updated
436   static Events_ID kUpdateSelection = Events_Loop::loop()->eventByName(EVENT_UPDATE_SELECTION);
437   ModelAPI_EventCreator::get()->sendUpdated(theMoved, kUpdateSelection, false);
438   ModelAPI_EventCreator::get()->sendReordered(theMoved);
439 }
440
441 void Model_Objects::clearHistory(ObjectPtr theObj)
442 {
443   if (theObj.get()) {
444     const std::string aGroup = theObj->groupName();
445     updateHistory(aGroup);
446
447     if (theObj->groupName() == ModelAPI_Feature::group()) { // clear results group of the feature
448       FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObj);
449       std::string aResultGroup = featureResultGroup(aFeature);
450       if (!aResultGroup.empty()) {
451         std::map<std::string, std::vector<ObjectPtr> >::iterator aHIter =
452           myHistory.find(aResultGroup);
453         if (aHIter != myHistory.end())
454           myHistory.erase(aHIter); // erase from map => this means that it is not synchronized
455       }
456     }
457   }
458 }
459
460 void Model_Objects::createHistory(const std::string& theGroupID)
461 {
462   std::map<std::string, std::vector<ObjectPtr> >::iterator aHIter = myHistory.find(theGroupID);
463   if (aHIter == myHistory.end()) {
464     std::vector<ObjectPtr> aResult;
465     std::vector<ObjectPtr> aResultOutOfFolder;
466     FeaturePtr aLastFeatureInFolder;
467     // iterate the array of references and get feature by feature from the array
468     bool isFeature = theGroupID == ModelAPI_Feature::group();
469     bool isFolder = theGroupID == ModelAPI_Folder::group();
470     Handle(TDataStd_ReferenceArray) aRefs;
471     if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
472       for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
473         FeaturePtr aFeature = feature(aRefs->Value(a));
474         if (aFeature.get()) {
475           // if feature is in sub-component, remove it from history:
476           // it is in sub-tree of sub-component
477           bool isSub = ModelAPI_Tools::compositeOwner(aFeature).get() != NULL;
478           if (isFeature) { // here may be also disabled features
479             if (!isSub && aFeature->isInHistory()) {
480               aResult.push_back(aFeature);
481               // the feature is out of the folders
482               if (aLastFeatureInFolder.get() == NULL)
483                 aResultOutOfFolder.push_back(aFeature);
484             }
485           } else if (!aFeature->isDisabled()) { // iterate all results of not-disabled feature
486             // construction results of sub-features should not be in the tree
487             if (!isSub || theGroupID != ModelAPI_ResultConstruction::group()) {
488               // do not use reference to the list here since results can be changed by "isConcealed"
489               const std::list<std::shared_ptr<ModelAPI_Result> > aResults = aFeature->results();
490               std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator
491                 aRIter = aResults.begin();
492               for (; aRIter != aResults.cend(); aRIter++) {
493                 ResultPtr aRes = *aRIter;
494                 if (aRes->groupName() != theGroupID) break; // feature have only same group results
495                 if (!aRes->isDisabled() && aRes->isInHistory() && !aRes->isConcealed()) {
496                   aResult.push_back(*aRIter);
497                 }
498               }
499             }
500           }
501
502           // the feature closes the folder, so the next features will be treated as out-of-folder
503           if (aLastFeatureInFolder.get() && aLastFeatureInFolder == aFeature)
504             aLastFeatureInFolder = FeaturePtr();
505
506         } else {
507           // it may be a folder
508           const ObjectPtr& aFolder = folder(aRefs->Value(a));
509           if (aFolder.get()) {
510             // store folder information for the Features group only
511             if (isFeature || isFolder) {
512               aResult.push_back(aFolder);
513               if (!isFolder)
514                 aResultOutOfFolder.push_back(aFolder);
515             }
516
517             // get the last feature in the folder
518             AttributeReferencePtr aLastFeatAttr =
519                 aFolder->data()->reference(ModelAPI_Folder::LAST_FEATURE_ID());
520             if (aLastFeatAttr)
521               aLastFeatureInFolder = ModelAPI_Feature::feature(aLastFeatAttr->value());
522           }
523         }
524       }
525     }
526     // to be sure that isConcealed did not update the history (issue 1089) during the iteration
527     if (myHistory.find(theGroupID) == myHistory.end()) {
528       myHistory[theGroupID] = aResult;
529
530       // store the features placed out of any folder
531       const std::string& anOutOfFolderGroupID = groupNameFoldering(theGroupID, true);
532       if (!anOutOfFolderGroupID.empty())
533         myHistory[anOutOfFolderGroupID] = aResultOutOfFolder;
534     }
535   }
536 }
537
538 void Model_Objects::updateHistory(const std::shared_ptr<ModelAPI_Object> theObject)
539 {
540   clearHistory(theObject);
541 }
542
543 void Model_Objects::updateHistory(const std::string theGroup)
544 {
545   std::map<std::string, std::vector<ObjectPtr> >::iterator aHIter = myHistory.find(theGroup);
546   if (aHIter != myHistory.end()) {
547     myHistory.erase(aHIter); // erase from map => this means that it is not synchronized
548
549     // erase history for the group of objects placed out of any folder
550     const std::string& anOutOfFolderGroupID = groupNameFoldering(theGroup, true);
551     if (!anOutOfFolderGroupID.empty())
552       myHistory.erase(anOutOfFolderGroupID);
553   }
554 }
555
556 const ObjectPtr& Model_Objects::folder(TDF_Label theLabel) const
557 {
558   if (myFolders.IsBound(theLabel))
559     return myFolders.Find(theLabel);
560   static ObjectPtr anEmptyResult;
561   return anEmptyResult;
562 }
563
564 FeaturePtr Model_Objects::feature(TDF_Label theLabel) const
565 {
566   if (myFeatures.IsBound(theLabel))
567     return myFeatures.Find(theLabel);
568   return FeaturePtr();  // not found
569 }
570
571 ObjectPtr Model_Objects::object(TDF_Label theLabel)
572 {
573   // try feature by label
574   FeaturePtr aFeature = feature(theLabel);
575   if (aFeature.get())
576     return feature(theLabel);
577   TDF_Label aFeatureLabel = theLabel;  // let's suppose it is result of this feature
578   TDF_LabelList aSubLabs; // sub - labels from higher level to lower level of result
579   while(!aFeature.get() && aFeatureLabel.Depth() > 1) {
580     aSubLabs.Prepend(aFeatureLabel);
581     aFeatureLabel = aFeatureLabel.Father().Father();
582     aFeature = feature(aFeatureLabel);
583   }
584   if (aFeature.get()) {
585     ResultPtr aCurrentResult;
586     // searching for results then sub-results label by label
587     for(TDF_ListIteratorOfLabelList aSubLab(aSubLabs); aSubLab.More(); aSubLab.Next()) {
588       if (aCurrentResult.get()) { // iterate sub-results of result
589         ResultBodyPtr anOwner = std::dynamic_pointer_cast<ModelAPI_ResultBody>(aCurrentResult);
590         if (!anOwner)
591           return ObjectPtr(); // only Body can have sub-results
592         int a, aNumSubs = anOwner->numberOfSubs();
593         for(a = 0; a < aNumSubs; a++) {
594           ResultPtr aSub = anOwner->subResult(a);
595           if (aSub.get()) {
596             std::shared_ptr<Model_Data> aSubData = std::dynamic_pointer_cast<Model_Data>(
597               aSub->data());
598             const TDF_Label& aSubLabVal = aSubLab.ChangeValue();
599             if (aSubData->label().Father().IsEqual(aSubLabVal)) {
600               aCurrentResult = aSub;
601               break;
602             }
603           }
604         }
605         if (a == aNumSubs) // not found an appropriate sub-result of result
606           return ObjectPtr();
607       } else { // iterate results of feature
608         const std::list<ResultPtr>& aResults = aFeature->results();
609         std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.cbegin();
610         for(; aRIter != aResults.cend(); aRIter++) {
611           std::shared_ptr<Model_Data> aResData =
612             std::dynamic_pointer_cast<Model_Data>((*aRIter)->data());
613           if (aResData->label().Father().IsEqual(aSubLab.ChangeValue())) {
614             aCurrentResult = *aRIter;
615             break;
616           }
617         }
618         if (aRIter == aResults.cend()) // not found an appropriate result of feature
619           return ObjectPtr();
620       }
621     }
622     return aCurrentResult;
623   }
624   return ObjectPtr();  // not found
625 }
626
627 ObjectPtr Model_Objects::object(const std::string& theGroupID,
628                                 const int theIndex,
629                                 const bool theAllowFolder)
630 {
631   if (theIndex == -1)
632     return ObjectPtr();
633   createHistory(theGroupID);
634   const std::string& aGroupID = groupNameFoldering(theGroupID, theAllowFolder);
635   return aGroupID.empty() ? myHistory[theGroupID][theIndex] : myHistory[aGroupID][theIndex];
636 }
637
638 std::shared_ptr<ModelAPI_Object> Model_Objects::objectByName(
639     const std::string& theGroupID, const std::wstring& theName)
640 {
641   createHistory(theGroupID);
642   if (theGroupID == ModelAPI_Feature::group()) { // searching among features (in history or not)
643     std::list<std::shared_ptr<ModelAPI_Feature> > allObjs = allFeatures();
644     // from the end to find the latest result with such name
645     std::list<std::shared_ptr<ModelAPI_Feature> >::reverse_iterator anObjIter = allObjs.rbegin();
646     for(; anObjIter != allObjs.rend(); anObjIter++) {
647       if ((*anObjIter)->data()->name() == theName)
648         return *anObjIter;
649     }
650   } else { // searching among results (concealed or not)
651     std::list<std::shared_ptr<ModelAPI_Feature> > allObjs = allFeatures();
652     // from the end to find the latest result with such name
653     std::list<std::shared_ptr<ModelAPI_Feature> >::reverse_iterator anObjIter = allObjs.rbegin();
654     for(; anObjIter != allObjs.rend(); anObjIter++) {
655       std::list<ResultPtr> allRes;
656       ModelAPI_Tools::allResults(*anObjIter, allRes);
657       for(std::list<ResultPtr>::iterator aRes = allRes.begin(); aRes != allRes.end(); aRes++) {
658         if (aRes->get() && (*aRes)->groupName() == theGroupID) {
659           if ((*aRes)->data()->name() == theName)
660             return *aRes;
661         }
662       }
663     }
664   }
665   // not found
666   return ObjectPtr();
667 }
668
669 const int Model_Objects::index(std::shared_ptr<ModelAPI_Object> theObject,
670                                const bool theAllowFolder)
671 {
672   std::string aGroup = theObject->groupName();
673   // treat folder as feature
674   if (aGroup == ModelAPI_Folder::group())
675     aGroup = ModelAPI_Feature::group();
676   createHistory(aGroup);
677
678   // get the group of features out of folder (if enabled)
679   if (theAllowFolder && !groupNameFoldering(aGroup, theAllowFolder).empty())
680     aGroup = groupNameFoldering(aGroup, theAllowFolder);
681
682   std::vector<ObjectPtr>& allObjs = myHistory[aGroup];
683   std::vector<ObjectPtr>::iterator anObjIter = allObjs.begin(); // iterate to search object
684   for(int anIndex = 0; anObjIter != allObjs.end(); anObjIter++, anIndex++) {
685     if ((*anObjIter) == theObject)
686       return anIndex;
687   }
688   // not found
689   return -1;
690 }
691
692 int Model_Objects::size(const std::string& theGroupID, const bool theAllowFolder)
693 {
694   createHistory(theGroupID);
695   const std::string& aGroupID = groupNameFoldering(theGroupID, theAllowFolder);
696   return aGroupID.empty() ? int(myHistory[theGroupID].size()) : int(myHistory[aGroupID].size());
697 }
698
699 std::shared_ptr<ModelAPI_Object> Model_Objects::parent(
700   const std::shared_ptr<ModelAPI_Object> theChild)
701 {
702   if (theChild.get()) {
703     std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(theChild->data());
704     TDF_Label aLab = aData->label();
705     if (!aLab.IsNull() && aLab.Depth() > 2) {
706       ObjectPtr anObj = object(aLab.Father().Father().Father());
707       return anObj;
708     }
709   }
710   return ObjectPtr();
711 }
712
713
714 void Model_Objects::allResults(const std::string& theGroupID, std::list<ResultPtr>& theResults)
715 {
716   // iterate the array of references and get feature by feature from the array
717   Handle(TDataStd_ReferenceArray) aRefs;
718   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
719     for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
720       FeaturePtr aFeature = feature(aRefs->Value(a));
721       if (aFeature.get()) {
722         const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
723         std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
724         for (; aRIter != aResults.cend(); aRIter++) {
725           ResultPtr aRes = *aRIter;
726           if (aRes->groupName() != theGroupID) break; // feature have only same group results
727           // iterate also concealed: ALL RESULTS (for translation parts undo/redo management)
728           //if (aRes->isInHistory() && !aRes->isConcealed()) {
729             theResults.push_back(*aRIter);
730           //}
731         }
732       }
733     }
734   }
735 }
736
737
738 TDF_Label Model_Objects::featuresLabel() const
739 {
740   return myMain.FindChild(TAG_OBJECTS);
741 }
742
743 static std::wstring composeName(const std::string& theFeatureKind, const int theIndex)
744 {
745   std::stringstream aNameStream;
746   aNameStream << theFeatureKind << "_" << theIndex;
747   return Locale::Convert::toWString(aNameStream.str());
748 }
749
750 void Model_Objects::setUniqueName(FeaturePtr theFeature)
751 {
752   if (!theFeature->data()->name().empty())
753     return;  // not needed, name is already defined
754   std::wstring aName;  // result
755   // first count all features of such kind to start with index = count + 1
756   int aNumObjects = -1; // this feature is already in this map
757   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myFeatures);
758   std::set<std::wstring> allNames;
759   for (; aFIter.More(); aFIter.Next()) {
760     if (aFIter.Value()->getKind() == theFeature->getKind())
761       aNumObjects++;
762     allNames.insert(aFIter.Value()->data()->name());
763   }
764   // generate candidate name
765   aName = composeName(theFeature->getKind(), aNumObjects + 1);
766   // check this is unique, if not, increase index by 1
767   for(aNumObjects++; allNames.find(aName) != allNames.end(); aNumObjects++) {
768     aName = composeName(theFeature->getKind(), aNumObjects + 1);
769   }
770   theFeature->data()->setName(aName);
771 }
772
773 void Model_Objects::setUniqueName(FolderPtr theFolder)
774 {
775   if (!theFolder->name().empty())
776     return; // name is already defined
777
778   int aNbFolders = myFolders.Size();
779   std::wstring aName = composeName(ModelAPI_Folder::ID(), aNbFolders);
780
781   // check the uniqueness of the name
782   NCollection_DataMap<TDF_Label, ObjectPtr>::Iterator anIt(myFolders);
783   while (anIt.More()) {
784     if (anIt.Value()->data()->name() == aName) {
785       aName = composeName(ModelAPI_Folder::ID(), ++aNbFolders);
786       // reinitialize iterator to make sure a new name is unique
787       anIt.Initialize(myFolders);
788     } else
789       anIt.Next();
790   }
791
792   theFolder->data()->setName(aName);
793 }
794
795 void Model_Objects::initData(ObjectPtr theObj, TDF_Label theLab, const int theTag)
796 {
797   std::shared_ptr<Model_Data> aData(new Model_Data);
798   aData->setLabel(theLab.FindChild(theTag));
799   aData->setObject(theObj);
800   theObj->setDoc(myDoc);
801   theObj->setData(aData);
802   FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObj);
803   if (aFeature.get()) {
804     setUniqueName(aFeature);  // must be before "initAttributes" because duplicate part uses name
805   } else { // is it a folder?
806     FolderPtr aFolder = std::dynamic_pointer_cast<ModelAPI_Folder>(theObj);
807     if (aFolder)
808       setUniqueName(aFolder);
809   }
810   theObj->initAttributes();
811 }
812
813 void Model_Objects::synchronizeFeatures(
814   const TDF_LabelList& theUpdated, const bool theUpdateReferences,
815   const bool theExecuteFeatures, const bool theOpen, const bool theFlush)
816 {
817   Model_Document* anOwner = std::dynamic_pointer_cast<Model_Document>(myDoc).get();
818   if (!anOwner) // this may happen on creation of document: nothing there, so nothing to synchronize
819     return;
820   // after all updates, sends a message that groups of features were created or updated
821   Events_Loop* aLoop = Events_Loop::loop();
822   //static Events_ID aDispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
823   static Events_ID aCreateEvent = aLoop->eventByName(EVENT_OBJECT_CREATED);
824   static Events_ID anUpdateEvent = aLoop->eventByName(EVENT_OBJECT_UPDATED);
825   static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
826   static Events_ID aDeleteEvent = aLoop->eventByName(EVENT_OBJECT_DELETED);
827   static Events_ID aToHideEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
828   bool isActive = aLoop->activateFlushes(false);
829
830   // collect all updated labels map
831   TDF_LabelMap anUpdatedMap;
832   TDF_ListIteratorOfLabelList anUpdatedIter(theUpdated);
833   for(; anUpdatedIter.More(); anUpdatedIter.Next()) {
834     TDF_Label& aFeatureLab = anUpdatedIter.Value();
835     while(aFeatureLab.Depth() > 3)
836       aFeatureLab = aFeatureLab.Father();
837     if (myFeatures.IsBound(aFeatureLab) || myFolders.IsBound(aFeatureLab))
838       anUpdatedMap.Add(aFeatureLab);
839   }
840
841   // update all objects by checking are they on labels or not
842   std::set<ObjectPtr> aNewFeatures, aKeptFeatures;
843   TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
844   for (; aLabIter.More(); aLabIter.Next()) {
845     TDF_Label aFeatureLabel = aLabIter.Value()->Label();
846     if (!myFeatures.IsBound(aFeatureLabel) && !myFolders.IsBound(aFeatureLabel)) {
847       // a new feature or folder is inserted
848
849       std::string aFeatureID = TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(
850                                aLabIter.Value())->Get()).ToCString();
851       bool isFolder = aFeatureID == ModelAPI_Folder::ID();
852
853       std::shared_ptr<Model_Session> aSession =
854           std::dynamic_pointer_cast<Model_Session>(ModelAPI_Session::get());
855
856       // create a feature
857       ObjectPtr aFeature = isFolder ? ObjectPtr(new ModelAPI_Folder)
858                                     : ObjectPtr(aSession->createFeature(aFeatureID, anOwner));
859       if (!aFeature.get()) {
860         // something is wrong, most probably, the opened document has invalid structure
861         Events_InfoMessage("Model_Objects", "Invalid type of object in the document").send();
862         aLabIter.Value()->Label().ForgetAllAttributes();
863         continue;
864       }
865       aFeature->init();
866       // this must be before "setData" to redo the sketch line correctly
867       if (isFolder)
868         myFolders.Bind(aFeatureLabel, aFeature);
869       else
870         myFeatures.Bind(aFeatureLabel, std::dynamic_pointer_cast<ModelAPI_Feature>(aFeature));
871       aNewFeatures.insert(aFeature);
872       initData(aFeature, aFeatureLabel, TAG_FEATURE_ARGUMENTS);
873       updateHistory(aFeature);
874
875       // event: model is updated
876       ModelAPI_EventCreator::get()->sendUpdated(aFeature, aCreateEvent);
877     } else {  // nothing is changed, both iterators are incremented
878       ObjectPtr anObject;
879       FeaturePtr aFeature;
880       if (myFeatures.Find(aFeatureLabel, aFeature)) {
881         aKeptFeatures.insert(aFeature);
882         anObject = aFeature;
883       } else
884         if (myFolders.Find(aFeatureLabel, anObject))
885           aKeptFeatures.insert(anObject);
886
887       if (anUpdatedMap.Contains(aFeatureLabel)) {
888         if (!theOpen) { // on abort/undo/redo reinitialize attributes if something is changed
889           FiltersFeaturePtr aFilter = std::dynamic_pointer_cast<ModelAPI_FiltersFeature>(anObject);
890           if (aFilter.get()) { // for filters attributes may be added/removed on undo/redo
891             std::dynamic_pointer_cast<Model_Data>(aFilter->data())->clearAttributes();
892             aFilter->initAttributes();
893           } else {
894             std::list<std::shared_ptr<ModelAPI_Attribute> > anAttrs =
895               anObject->data()->attributes("");
896             std::list<std::shared_ptr<ModelAPI_Attribute> >::iterator anAttr = anAttrs.begin();
897             for(; anAttr != anAttrs.end(); anAttr++)
898               (*anAttr)->reinit();
899             // if feature contains results, re-init them too
900             if (aFeature.get()) {
901               std::list<ResultPtr> aResults;
902               ModelAPI_Tools::allResults(aFeature, aResults);
903               std::list<ResultPtr>::iterator aResIter = aResults.begin();
904               for(; aResIter != aResults.end(); aResIter++) {
905                 anAttrs = (*aResIter)->data()->attributes("");
906                 for(anAttr = anAttrs.begin(); anAttr != anAttrs.end(); anAttr++)
907                   (*anAttr)->reinit();
908               }
909             }
910           }
911         }
912         ModelAPI_EventCreator::get()->sendUpdated(anObject, anUpdateEvent);
913         if (aFeature && aFeature->getKind() == "Parameter") {
914           // if parameters are changed, update the results (issue 937)
915           const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
916           std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
917           for (; aRIter != aResults.cend(); aRIter++) {
918             std::shared_ptr<ModelAPI_Result> aRes = *aRIter;
919             if (aRes->data()->isValid() && !aRes->isDisabled()) {
920               ModelAPI_EventCreator::get()->sendUpdated(aRes, anUpdateEvent);
921             }
922           }
923         }
924       }
925     }
926   }
927
928   // check all features are checked: if not => it was removed
929   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myFeatures);
930   while (aFIter.More()) {
931     if (aKeptFeatures.find(aFIter.Value()) == aKeptFeatures.end()
932       && aNewFeatures.find(aFIter.Value()) == aNewFeatures.end()) {
933         FeaturePtr aFeature = aFIter.Value();
934         // event: model is updated
935         //if (aFeature->isInHistory()) {
936         ModelAPI_EventCreator::get()->sendDeleted(myDoc, ModelAPI_Feature::group());
937         //}
938         // results of this feature must be redisplayed (hided)
939         // redisplay also removed feature (used for sketch and AISObject)
940         ModelAPI_EventCreator::get()->sendUpdated(aFeature, aRedispEvent);
941         updateHistory(aFeature);
942         aFeature->erase();
943
944         // unbind after the "erase" call: on abort sketch
945         // is removes sub-objects that corrupts aFIter
946         myFeatures.UnBind(aFIter.Key());
947         // reinitialize iterator because unbind may corrupt the previous order in the map
948         aFIter.Initialize(myFeatures);
949     } else
950       aFIter.Next();
951   }
952   // verify folders are checked: if not => is was removed
953   for (NCollection_DataMap<TDF_Label, ObjectPtr>::Iterator aFldIt(myFolders);
954        aFldIt.More(); aFldIt.Next()) {
955     ObjectPtr aCurObj = aFldIt.Value();
956     if (aKeptFeatures.find(aCurObj) == aKeptFeatures.end() &&
957         aNewFeatures.find(aCurObj) == aNewFeatures.end()) {
958       ModelAPI_EventCreator::get()->sendDeleted(myDoc, ModelAPI_Folder::group());
959       // results of this feature must be redisplayed (hided)
960       // redisplay also removed feature (used for sketch and AISObject)
961       ModelAPI_EventCreator::get()->sendUpdated(aCurObj, aRedispEvent);
962       updateHistory(aCurObj);
963       aCurObj->erase();
964
965       // unbind after the "erase" call: on abort sketch
966       // is removes sub-objects that corrupts aFIter
967       myFolders.UnBind(aFldIt.Key());
968       // reinitialize iterator because unbind may corrupt the previous order in the map
969       aFldIt.Initialize(myFolders);
970     }
971   }
972
973   if (theUpdateReferences) {
974     synchronizeBackRefs();
975   }
976   // update results of the features (after features created because
977   // they may be connected, like sketch and sub elements)
978   // After synchronization of back references because sketch
979   // must be set in sub-elements before "execute" by updateResults
980   std::set<FeaturePtr> aProcessed; // composites must be updated after their subs (issue 360)
981   TDF_ChildIDIterator aLabIter2(featuresLabel(), TDataStd_Comment::GetID());
982   for (; aLabIter2.More(); aLabIter2.Next()) {
983     TDF_Label aFeatureLabel = aLabIter2.Value()->Label();
984     if (myFeatures.IsBound(aFeatureLabel)) {  // a new feature is inserted
985       FeaturePtr aFeature = myFeatures.Find(aFeatureLabel);
986       updateResults(aFeature, aProcessed);
987     }
988   }
989   // the synchronize should be done after updateResults
990   // in order to correct back references of updated results
991   if (theUpdateReferences) {
992     synchronizeBackRefs();
993   }
994   if (!theUpdated.IsEmpty()) {
995     // this means there is no control what was modified => remove history cash
996     myHistory.clear();
997   }
998
999   if (!theExecuteFeatures)
1000     anOwner->setExecuteFeatures(false);
1001   aLoop->activateFlushes(isActive);
1002
1003   if (theFlush) {
1004     aLoop->flush(aDeleteEvent);
1005     // delete should be emitted before create to reacts to aborted feature
1006     aLoop->flush(aCreateEvent);
1007     aLoop->flush(anUpdateEvent);
1008     aLoop->flush(aCreateEvent); // after update of features, there could be results created
1009     aLoop->flush(aDeleteEvent); // or deleted
1010     aLoop->flush(aRedispEvent);
1011     aLoop->flush(aToHideEvent);
1012   }
1013   if (!theExecuteFeatures)
1014     anOwner->setExecuteFeatures(true);
1015 }
1016
1017 /// synchronizes back references for the given object basing on the collected data
1018 void Model_Objects::synchronizeBackRefsForObject(const std::set<AttributePtr>& theNewRefs,
1019   ObjectPtr theObject)
1020 {
1021   if (!theObject.get() || !theObject->data()->isValid())
1022     return; // invalid
1023   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(theObject->data());
1024   // iterate new list to compare with current
1025   std::set<AttributePtr>::iterator aNewIter = theNewRefs.begin();
1026   for(; aNewIter != theNewRefs.end(); aNewIter++) {
1027     // for the Model_AttributeRefList erase cash (issue #2819)
1028     std::shared_ptr<Model_AttributeRefList> aRefList =
1029       std::dynamic_pointer_cast<Model_AttributeRefList>(*aNewIter);
1030     if (aRefList)
1031       aRefList->eraseHash();
1032
1033     if (aData->refsToMe().find(*aNewIter) == aData->refsToMe().end()) {
1034       FeaturePtr aRefFeat = std::dynamic_pointer_cast<ModelAPI_Feature>((*aNewIter)->owner());
1035       if (aRefFeat)
1036         aData->addBackReference(aRefFeat, (*aNewIter)->id());
1037       else // add back reference to a folder
1038         aData->addBackReference((*aNewIter)->owner(), (*aNewIter)->id());
1039     }
1040   }
1041   if (theNewRefs.size() != aData->refsToMe().size()) { // some back ref must be removed
1042     std::set<AttributePtr>::iterator aCurrentIter = aData->refsToMe().begin();
1043     while(aCurrentIter != aData->refsToMe().end()) {
1044       if (theNewRefs.find(*aCurrentIter) == theNewRefs.end()) {
1045         // for external references from other documents this system
1046         // is not working: refs are collected from
1047         // different Model_Objects, so before remove check this
1048         // external object exists and still referenced
1049         bool aLeaveIt = false;
1050         if ((*aCurrentIter)->owner().get() && (*aCurrentIter)->owner()->document() != myDoc &&
1051             (*aCurrentIter)->owner()->data().get() && (*aCurrentIter)->owner()->data()->isValid()) {
1052           std::list<std::pair<std::string, std::list<std::shared_ptr<ModelAPI_Object> > > > aRefs;
1053           (*aCurrentIter)->owner()->data()->referencesToObjects(aRefs);
1054           std::list<std::pair<std::string, std::list<std::shared_ptr<ModelAPI_Object> >>>::iterator
1055             aRefIter = aRefs.begin();
1056           for(; aRefIter != aRefs.end(); aRefIter++) {
1057             if ((*aCurrentIter)->id() == aRefIter->first) {
1058               std::list<std::shared_ptr<ModelAPI_Object> >::iterator anOIt;
1059               for(anOIt = aRefIter->second.begin(); anOIt != aRefIter->second.end(); anOIt++) {
1060                 if (*anOIt == theObject) {
1061                   aLeaveIt = true;
1062                 }
1063               }
1064             }
1065           }
1066         }
1067         if (!aLeaveIt) {
1068           aData->removeBackReference(*aCurrentIter);
1069           aCurrentIter = aData->refsToMe().begin(); // reinitialize iteration after delete
1070         } else aCurrentIter++;
1071       } else aCurrentIter++;
1072     }
1073   }
1074   // for the last feature in the folder, check if it is a sub-feature,
1075   // then refer the folder to a top-level parent composite feature
1076   const std::set<AttributePtr>& aRefs = aData->refsToMe();
1077   std::set<AttributePtr>::iterator anIt = aRefs.begin();
1078   for (; anIt != aRefs.end(); ++anIt)
1079     if ((*anIt)->id() == ModelAPI_Folder::LAST_FEATURE_ID())
1080       break;
1081   if (anIt != aRefs.end()) {
1082     FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
1083     if (aFeature) {
1084       CompositeFeaturePtr aParent;
1085       CompositeFeaturePtr aGrandParent = ModelAPI_Tools::compositeOwner(aFeature);
1086       do {
1087         aParent = aGrandParent;
1088         if (aGrandParent)
1089           aGrandParent = ModelAPI_Tools::compositeOwner(aParent);
1090       } while (aGrandParent.get());
1091       if (aParent) {
1092         ObjectPtr aFolder = (*anIt)->owner();
1093         // remove reference from the current feature
1094         aData->removeBackReference(aFolder, ModelAPI_Folder::LAST_FEATURE_ID());
1095         // set reference to a top-level parent
1096         aFolder->data()->reference(ModelAPI_Folder::LAST_FEATURE_ID())->setValue(aParent);
1097         std::shared_ptr<Model_Data> aParentData =
1098             std::dynamic_pointer_cast<Model_Data>(aParent->data());
1099         aParentData->addBackReference(aFolder, ModelAPI_Folder::LAST_FEATURE_ID());
1100       }
1101     }
1102   }
1103   aData->updateConcealmentFlag();
1104 }
1105
1106 static void collectReferences(std::shared_ptr<ModelAPI_Data> theData,
1107                               std::map<ObjectPtr, std::set<AttributePtr> >& theRefs)
1108 {
1109   if (theData.get()) {
1110     std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
1111     theData->referencesToObjects(aRefs);
1112     std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator aRefsIt = aRefs.begin();
1113     for(; aRefsIt != aRefs.end(); aRefsIt++) {
1114       std::list<ObjectPtr>::iterator aRefTo = aRefsIt->second.begin();
1115       for(; aRefTo != aRefsIt->second.end(); aRefTo++) {
1116         if (*aRefTo) {
1117           std::map<ObjectPtr, std::set<AttributePtr> >::iterator aFound = theRefs.find(*aRefTo);
1118           if (aFound == theRefs.end()) {
1119             theRefs[*aRefTo] = std::set<AttributePtr>();
1120             aFound = theRefs.find(*aRefTo);
1121           }
1122           aFound->second.insert(theData->attribute(aRefsIt->first));
1123         }
1124       }
1125     }
1126   }
1127 }
1128
1129 void Model_Objects::synchronizeBackRefs()
1130 {
1131   // collect all back references in the separated container: to update everything at once,
1132   // without additional Concealment switching on and off: only the final modification
1133
1134   // referenced (slave) objects to referencing attributes
1135   std::map<ObjectPtr, std::set<AttributePtr> > allRefs;
1136   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFeatures(myFeatures);
1137   for(; aFeatures.More(); aFeatures.Next()) {
1138     FeaturePtr aFeature = aFeatures.Value();
1139     collectReferences(aFeature->data(), allRefs);
1140   }
1141   NCollection_DataMap<TDF_Label, ObjectPtr>::Iterator aFolders(myFolders);
1142   for(; aFolders.More(); aFolders.Next()) {
1143     ObjectPtr aFolder = aFolders.Value();
1144     collectReferences(aFolder->data(), allRefs);
1145   }
1146   // second iteration: just compare back-references with existing in features and results
1147   for(aFeatures.Initialize(myFeatures); aFeatures.More(); aFeatures.Next()) {
1148     FeaturePtr aFeature = aFeatures.Value();
1149     static std::set<AttributePtr> anEmpty;
1150     std::map<ObjectPtr, std::set<AttributePtr> >::iterator aFound = allRefs.find(aFeature);
1151     if (aFound == allRefs.end()) { // not found => erase all back references
1152       synchronizeBackRefsForObject(anEmpty, aFeature);
1153     } else {
1154       synchronizeBackRefsForObject(aFound->second, aFeature);
1155       allRefs.erase(aFound); // to check that all refs are counted
1156     }
1157     // also for results
1158     std::list<ResultPtr> aResults;
1159     ModelAPI_Tools::allResults(aFeature, aResults);
1160     std::list<ResultPtr>::iterator aRIter = aResults.begin();
1161     for(; aRIter != aResults.cend(); aRIter++) {
1162       aFound = allRefs.find(*aRIter);
1163       if (aFound == allRefs.end()) { // not found => erase all back references
1164         synchronizeBackRefsForObject(anEmpty, *aRIter);
1165       } else {
1166         synchronizeBackRefsForObject(aFound->second, *aRIter);
1167         allRefs.erase(aFound); // to check that all refs are counted
1168       }
1169     }
1170   }
1171   for(aFeatures.Initialize(myFeatures); aFeatures.More(); aFeatures.Next()) {
1172     FeaturePtr aFeature = aFeatures.Value();
1173     std::list<ResultPtr> aResults;
1174     ModelAPI_Tools::allResults(aFeature, aResults);
1175     // update the concealment status for display in isConcealed of ResultBody
1176     std::list<ResultPtr>::iterator aRIter = aResults.begin();
1177     for(; aRIter != aResults.cend(); aRIter++) {
1178       (*aRIter)->isConcealed();
1179     }
1180   }
1181   // the rest all refs means that feature references to the external document feature:
1182   // process also them
1183   std::map<ObjectPtr, std::set<AttributePtr> >::iterator anExtIter = allRefs.begin();
1184   for(; anExtIter != allRefs.end(); anExtIter++) {
1185     synchronizeBackRefsForObject(anExtIter->second, anExtIter->first);
1186   }
1187 }
1188
1189 TDF_Label Model_Objects::resultLabel(
1190   const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theResultIndex)
1191 {
1192   const std::shared_ptr<Model_Data>& aData =
1193     std::dynamic_pointer_cast<Model_Data>(theFeatureData);
1194   return aData->label().Father().FindChild(TAG_FEATURE_RESULTS).FindChild(theResultIndex + 1);
1195 }
1196
1197 bool Model_Objects::hasCustomName(DataPtr theFeatureData,
1198                                   ResultPtr theResult,
1199                                   int /*theResultIndex*/,
1200                                   std::wstring& theParentName) const
1201 {
1202   ResultBodyPtr aBodyRes = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theFeatureData->owner());
1203   if (aBodyRes) {
1204     // only for top-results (works for the cases when results are not yet added to the feature)
1205     FeaturePtr anOwner = ModelAPI_Feature::feature(theResult);
1206
1207     // names of sub-solids in CompSolid should be default (for example,
1208     // result of boolean operation 'Boolean_1' is a CompSolid which is renamed to 'MyBOOL',
1209     // however, sub-elements of 'MyBOOL' should be named 'Boolean_1_1', 'Boolean_1_2' etc.)
1210     if (std::dynamic_pointer_cast<Model_Data>(aBodyRes->data())->label().Depth() == 6) {
1211       std::wostringstream aDefaultName;
1212       // compute default name of CompSolid (name of feature + index of CompSolid's result)
1213       int aBodyResultIndex = 0;
1214       const std::list<ResultPtr>& aResults = anOwner->results();
1215       std::list<ResultPtr>::const_iterator anIt = aResults.begin();
1216       for (; anIt != aResults.end(); ++anIt, ++aBodyResultIndex)
1217         if (aBodyRes == *anIt)
1218           break;
1219       aDefaultName << anOwner->name();
1220       aDefaultName << "_" << (aBodyResultIndex + 1);
1221       theParentName = aDefaultName.str();
1222     } else { // just name of the parent result if it is deeper than just a sub-result
1223       theParentName = aBodyRes->data()->name();
1224     }
1225     return false;
1226   }
1227
1228   std::pair<std::wstring, bool> aName = ModelAPI_Tools::getDefaultName(theResult);
1229   if (aName.second)
1230     theParentName = aName.first;
1231   return aName.second;
1232 }
1233
1234 void Model_Objects::storeResult(std::shared_ptr<ModelAPI_Data> theFeatureData,
1235                                 std::shared_ptr<ModelAPI_Result> theResult,
1236                                 const int theResultIndex,
1237                                 const std::wstring& theNameShape)
1238 {
1239   theResult->init();
1240   theResult->setDoc(myDoc);
1241   initData(theResult, resultLabel(theFeatureData, theResultIndex), TAG_FEATURE_ARGUMENTS);
1242   if (theResult->data()->name().empty()) {
1243     // if was not initialized, generate event and set a name
1244     std::wstring aNewName = theFeatureData->name();
1245     if (hasCustomName(theFeatureData, theResult, theResultIndex, aNewName)) {
1246       // if the name of result is user-defined, then, at first time, assign name of the result
1247       // by empty string to be sure that corresponding flag in the data model is set
1248       theResult->data()->setName(L"");
1249     } else {
1250       std::wstringstream aName;
1251       if ( theNameShape != L"" ){
1252         aName << theNameShape;
1253       } else {
1254         aName << aNewName;
1255         // if there are several results (issue #899: any number of result),
1256         // add unique prefix starting from second
1257         if (theResultIndex > 0 || theResult->groupName() == ModelAPI_ResultBody::group())
1258           aName << "_" << theResultIndex + 1;
1259       }
1260       aNewName = aName.str();
1261     }
1262     theResult->data()->setName(aNewName);
1263   }
1264 }
1265
1266 std::shared_ptr<ModelAPI_ResultConstruction> Model_Objects::createConstruction(
1267     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1268 {
1269   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1270   TDataStd_Comment::Set(aLab, ModelAPI_ResultConstruction::group().c_str());
1271   ObjectPtr anOldObject = object(aLab);
1272   std::shared_ptr<ModelAPI_ResultConstruction> aResult;
1273   if (anOldObject.get()) {
1274     aResult = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(anOldObject);
1275   }
1276   if (!aResult.get()) {
1277     aResult = std::shared_ptr<ModelAPI_ResultConstruction>(new Model_ResultConstruction);
1278     storeResult(theFeatureData, aResult, theIndex);
1279   }
1280   return aResult;
1281 }
1282
1283 std::shared_ptr<ModelAPI_ResultBody> Model_Objects::createBody(
1284     const std::shared_ptr<ModelAPI_Data>& theFeatureData,
1285     const int theIndex,
1286     const std::wstring& theNameShape)
1287 {
1288   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1289   TDataStd_Comment::Set(aLab, ModelAPI_ResultBody::group().c_str());
1290   ObjectPtr anOldObject = object(aLab);
1291   std::shared_ptr<ModelAPI_ResultBody> aResult;
1292   if (anOldObject.get()) {
1293     aResult = std::dynamic_pointer_cast<ModelAPI_ResultBody>(anOldObject);
1294   }
1295   if (!aResult.get()) {
1296     aResult = std::shared_ptr<ModelAPI_ResultBody>(new Model_ResultBody);
1297     storeResult(theFeatureData, aResult, theIndex, theNameShape);
1298   }
1299   return aResult;
1300 }
1301
1302 std::shared_ptr<ModelAPI_ResultPart> Model_Objects::createPart(
1303     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1304 {
1305   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1306   TDataStd_Comment::Set(aLab, ModelAPI_ResultPart::group().c_str());
1307   ObjectPtr anOldObject = object(aLab);
1308   std::shared_ptr<ModelAPI_ResultPart> aResult;
1309   if (anOldObject.get()) {
1310     aResult = std::dynamic_pointer_cast<ModelAPI_ResultPart>(anOldObject);
1311   }
1312   if (!aResult.get()) {
1313     aResult = std::shared_ptr<ModelAPI_ResultPart>(new Model_ResultPart);
1314     storeResult(theFeatureData, aResult, theIndex);
1315   }
1316   return aResult;
1317 }
1318
1319 std::shared_ptr<ModelAPI_ResultPart> Model_Objects::copyPart(
1320     const std::shared_ptr<ModelAPI_ResultPart>& theOrigin,
1321     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1322 {
1323   std::shared_ptr<ModelAPI_ResultPart> aResult = createPart(theFeatureData, theIndex);
1324   aResult->data()->reference(Model_ResultPart::BASE_REF_ID())->setValue(theOrigin);
1325   return aResult;
1326 }
1327
1328 std::shared_ptr<ModelAPI_ResultGroup> Model_Objects::createGroup(
1329     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1330 {
1331   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1332   TDataStd_Comment::Set(aLab, ModelAPI_ResultGroup::group().c_str());
1333   ObjectPtr anOldObject = object(aLab);
1334   std::shared_ptr<ModelAPI_ResultGroup> aResult;
1335   if (anOldObject.get()) {
1336     aResult = std::dynamic_pointer_cast<ModelAPI_ResultGroup>(anOldObject);
1337   }
1338   if (!aResult.get()) {
1339     aResult = std::shared_ptr<ModelAPI_ResultGroup>(new Model_ResultGroup(theFeatureData));
1340     storeResult(theFeatureData, aResult, theIndex);
1341   }
1342   return aResult;
1343 }
1344
1345 std::shared_ptr<ModelAPI_ResultField> Model_Objects::createField(
1346     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1347 {
1348   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1349   TDataStd_Comment::Set(aLab, ModelAPI_ResultField::group().c_str());
1350   ObjectPtr anOldObject = object(aLab);
1351   std::shared_ptr<ModelAPI_ResultField> aResult;
1352   if (anOldObject.get()) {
1353     aResult = std::dynamic_pointer_cast<ModelAPI_ResultField>(anOldObject);
1354   }
1355   if (!aResult.get()) {
1356     aResult = std::shared_ptr<ModelAPI_ResultField>(new Model_ResultField(theFeatureData));
1357     storeResult(theFeatureData, aResult, theIndex);
1358   }
1359   return aResult;
1360 }
1361
1362 std::shared_ptr<ModelAPI_ResultParameter> Model_Objects::createParameter(
1363       const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1364 {
1365   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1366   TDataStd_Comment::Set(aLab, ModelAPI_ResultParameter::group().c_str());
1367   ObjectPtr anOldObject = object(aLab);
1368   std::shared_ptr<ModelAPI_ResultParameter> aResult;
1369   if (anOldObject.get()) {
1370     aResult = std::dynamic_pointer_cast<ModelAPI_ResultParameter>(anOldObject);
1371   }
1372   if (!aResult.get()) {
1373     aResult = std::shared_ptr<ModelAPI_ResultParameter>(new Model_ResultParameter);
1374     storeResult(theFeatureData, aResult, theIndex);
1375   }
1376   return aResult;
1377 }
1378
1379 std::shared_ptr<ModelAPI_Folder> Model_Objects::createFolder(
1380     const std::shared_ptr<ModelAPI_Feature>& theBeforeThis)
1381 {
1382   FolderPtr aFolder(new ModelAPI_Folder);
1383   if (!aFolder)
1384     return aFolder;
1385
1386   TDF_Label aFeaturesLab = featuresLabel();
1387   TDF_Label aFolderLab = aFeaturesLab.NewChild();
1388   // store feature in the features array: before "initData" because in macro features
1389   // in initData it creates new features, appeared later than this
1390   TDF_Label aPrevFeatureLab;
1391   if (theBeforeThis.get()) { // searching for the previous feature label
1392     std::shared_ptr<Model_Data> aPrevData =
1393         std::dynamic_pointer_cast<Model_Data>(theBeforeThis->data());
1394     if (aPrevData.get()) {
1395       int anIndex = kUNDEFINED_FEATURE_INDEX;
1396       aPrevFeatureLab = nextLabel(aPrevData->label().Father(), anIndex, true);
1397     }
1398   } else { // find the label of the last feature
1399     Handle(TDataStd_ReferenceArray) aRefs;
1400     if (aFeaturesLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
1401       aPrevFeatureLab = aRefs->Value(aRefs->Upper());
1402   }
1403   AddToRefArray(aFeaturesLab, aFolderLab, aPrevFeatureLab);
1404
1405   // keep the feature ID to restore document later correctly
1406   TDataStd_Comment::Set(aFolderLab, ModelAPI_Folder::ID().c_str());
1407   myFolders.Bind(aFolderLab, aFolder);
1408   // must be before the event sending: for OB the feature is already added
1409   updateHistory(ModelAPI_Folder::group());
1410   updateHistory(ModelAPI_Feature::group());
1411
1412   // must be after binding to the map because of "Box" macro feature that
1413   // creates other features in "initData"
1414   initData(aFolder, aFolderLab, TAG_FEATURE_ARGUMENTS);
1415   // event: folder is added, must be before "initData" to update OB correctly on Duplicate:
1416   // first new part, then the content
1417   static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
1418   ModelAPI_EventCreator::get()->sendUpdated(aFolder, anEvent);
1419
1420   return aFolder;
1421 }
1422
1423 void Model_Objects::removeFolder(std::shared_ptr<ModelAPI_Folder> theFolder)
1424 {
1425   std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theFolder->data());
1426   if (!aData.get() || !aData->isValid())
1427     return;
1428
1429   // this must be before erase since theFolder erasing removes all information about it
1430   clearHistory(theFolder);
1431   // erase fields
1432   theFolder->erase();
1433
1434   TDF_Label aFolderLabel = aData->label().Father();
1435   if (myFolders.IsBound(aFolderLabel))
1436     myFolders.UnBind(aFolderLabel);
1437
1438   static Events_ID EVENT_DISP = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
1439   ModelAPI_EventCreator::get()->sendUpdated(theFolder, EVENT_DISP);
1440   // erase all attributes under the label of feature
1441   aFolderLabel.ForgetAllAttributes();
1442   // remove it from the references array
1443   RemoveFromRefArray(featuresLabel(), aFolderLabel);
1444   // event: feature is deleted
1445   ModelAPI_EventCreator::get()->sendDeleted(theFolder->document(), ModelAPI_Folder::group());
1446   updateHistory(ModelAPI_Folder::group());
1447   updateHistory(ModelAPI_Feature::group());
1448 }
1449
1450 // Returns one of the limiting features of the list
1451 static FeaturePtr limitingFeature(std::list<FeaturePtr>& theFeatures, const bool isLast)
1452 {
1453   FeaturePtr aFeature;
1454   if (isLast) {
1455     aFeature = theFeatures.back();
1456     theFeatures.pop_back();
1457   } else {
1458     aFeature = theFeatures.front();
1459     theFeatures.pop_front();
1460   }
1461   return aFeature;
1462 }
1463
1464 // Verify the feature is sub-element in composite feature or it is not used in the history
1465 static bool isSkippedFeature(FeaturePtr theFeature)
1466 {
1467   bool isSub = ModelAPI_Tools::compositeOwner(theFeature).get() != NULL;
1468   return isSub || (theFeature && !theFeature->isInHistory());
1469 }
1470
1471 std::shared_ptr<ModelAPI_Folder> Model_Objects::findFolder(
1472       const std::list<std::shared_ptr<ModelAPI_Feature> >& theFeatures,
1473       const bool theBelow)
1474 {
1475   if (theFeatures.empty())
1476     return FolderPtr(); // nothing to move
1477
1478   TDF_Label aFeaturesLab = featuresLabel();
1479   Handle(TDataStd_ReferenceArray) aRefs;
1480   if (!aFeaturesLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
1481     return FolderPtr(); // no reference array (something is wrong)
1482
1483   std::list<std::shared_ptr<ModelAPI_Feature> > aFeatures = theFeatures;
1484   std::shared_ptr<ModelAPI_Feature> aLimitingFeature = limitingFeature(aFeatures, theBelow);
1485
1486   std::shared_ptr<Model_Data> aData =
1487       std::static_pointer_cast<Model_Data>(aLimitingFeature->data());
1488   if (!aData || !aData->isValid())
1489     return FolderPtr(); // invalid feature
1490
1491   // label of the first feature in the list for fast searching
1492   TDF_Label aFirstFeatureLabel = aData->label().Father();
1493
1494   // find a folder above the features and
1495   // check the given features represent a sequential list of objects following the folder
1496   FolderPtr aFoundFolder;
1497   TDF_Label aLastFeatureInFolder;
1498   int aRefIndex = aRefs->Lower();
1499   for(; aRefIndex <= aRefs->Upper(); ++aRefIndex) { // iterate all existing features
1500     TDF_Label aCurLabel = aRefs->Value(aRefIndex);
1501     if (aCurLabel.IsEqual(aFirstFeatureLabel))
1502       break; // no need to continue searching
1503
1504     // searching the folder below, just continue to search last feature from the list
1505     if (theBelow)
1506       continue;
1507
1508     // issue #18733: check for the last feature in folder before checking the sub-feature,
1509     //               because the folder may end by the feature which is
1510     //               neither a sub-feature nor a feature in history.
1511     if (!aLastFeatureInFolder.IsNull()) {
1512       if (aCurLabel.IsEqual(aLastFeatureInFolder))
1513         aLastFeatureInFolder.Nullify(); // the last feature in the folder is achieved
1514       continue;
1515     }
1516
1517     // if feature is in sub-component, skip it
1518     FeaturePtr aCurFeature = feature(aCurLabel);
1519     if (isSkippedFeature(aCurFeature))
1520       continue;
1521
1522     const ObjectPtr& aFolderObj = folder(aCurLabel);
1523     if (aFolderObj.get()) {
1524       aFoundFolder = std::dynamic_pointer_cast<ModelAPI_Folder>(aFolderObj);
1525       AttributeReferencePtr aLastFeatAttr =
1526           aFoundFolder->reference(ModelAPI_Folder::LAST_FEATURE_ID());
1527       if (aLastFeatAttr) {
1528         // setup iterating inside a folder to find last feature
1529         ObjectPtr aLastFeature = aLastFeatAttr->value();
1530         if (aLastFeature) {
1531           aData = std::static_pointer_cast<Model_Data>(aLastFeature->data());
1532           if (aData && aData->isValid())
1533             aLastFeatureInFolder = aData->label().Father();
1534         }
1535       }
1536     }
1537   }
1538
1539   if (theBelow && aRefIndex < aRefs->Upper()) {
1540     TDF_Label aLabel;
1541     // skip following features which are sub-components or not in history
1542     for (int anIndex = aRefIndex + 1; anIndex <= aRefs->Upper(); ++anIndex) {
1543       aLabel = aRefs->Value(anIndex);
1544       FeaturePtr aCurFeature = feature(aLabel);
1545       if (!isSkippedFeature(aCurFeature))
1546         break;
1547     }
1548     // check the next object is a folder
1549     aFoundFolder = std::dynamic_pointer_cast<ModelAPI_Folder>(folder(aLabel));
1550   }
1551
1552   if (!aLastFeatureInFolder.IsNull() || // the last feature of the folder above is not found
1553       !aFoundFolder)
1554     return FolderPtr();
1555
1556   // check the given features are sequential list
1557   int aStep = theBelow ? -1 : 1;
1558   for (aRefIndex += aStep;
1559        !aFeatures.empty() && aRefIndex >= aRefs->Lower() && aRefIndex <= aRefs->Upper();
1560        aRefIndex += aStep) {
1561     TDF_Label aCurLabel = aRefs->Value(aRefIndex);
1562     // if feature is in sub-component, skip it
1563     FeaturePtr aCurFeature = feature(aCurLabel);
1564     if (isSkippedFeature(aCurFeature))
1565       continue;
1566
1567     aLimitingFeature = limitingFeature(aFeatures, theBelow);
1568     if (!aCurFeature->data()->isEqual(aLimitingFeature->data()))
1569       return FolderPtr(); // not a sequential list
1570   }
1571
1572   return aFoundFolder;
1573 }
1574
1575 bool Model_Objects::moveToFolder(
1576       const std::list<std::shared_ptr<ModelAPI_Feature> >& theFeatures,
1577       const std::shared_ptr<ModelAPI_Folder>& theFolder)
1578 {
1579   if (theFeatures.empty() || !theFolder)
1580     return false;
1581
1582   // labels for the folder and last feature in the list
1583   TDF_Label aFolderLabel, aLastFeatureLabel;
1584   std::shared_ptr<Model_Data> aData =
1585       std::static_pointer_cast<Model_Data>(theFolder->data());
1586   if (aData && aData->isValid())
1587     aFolderLabel = aData->label().Father();
1588   aData = std::static_pointer_cast<Model_Data>(theFeatures.back()->data());
1589   if (aData && aData->isValid())
1590     aLastFeatureLabel = aData->label().Father();
1591
1592   if (aFolderLabel.IsNull() || aLastFeatureLabel.IsNull())
1593     return false;
1594
1595   AttributeReferencePtr aFirstFeatAttr =
1596       theFolder->reference(ModelAPI_Folder::FIRST_FEATURE_ID());
1597   AttributeReferencePtr aLastFeatAttr =
1598       theFolder->reference(ModelAPI_Folder::LAST_FEATURE_ID());
1599   bool initFirstAttr = !aFirstFeatAttr->value().get();
1600   bool initLastAttr  = !aLastFeatAttr->value().get();
1601
1602   // check the folder is below the list of features
1603   bool isFolderBelow = false;
1604   TDF_Label aFeaturesLab = featuresLabel();
1605   Handle(TDataStd_ReferenceArray) aRefs;
1606   if (!aFeaturesLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
1607     return false; // no reference array (something is wrong)
1608   for (int aRefIndex = aRefs->Lower(); aRefIndex <= aRefs->Upper(); ++aRefIndex) {
1609     TDF_Label aCurLabel = aRefs->Value(aRefIndex);
1610     if (aCurLabel == aFolderLabel)
1611       break; // folder is above the features
1612     else if (aCurLabel == aLastFeatureLabel) {
1613       isFolderBelow = true;
1614       break;
1615     }
1616   }
1617
1618   if (isFolderBelow) {
1619     aData = std::static_pointer_cast<Model_Data>(theFeatures.front()->data());
1620     if (!aData || !aData->isValid())
1621       return false;
1622     TDF_Label aPrevFeatureLabel = aData->label().Father();
1623     // label of the feature before the first feature in the list
1624     for (int aRefIndex = aRefs->Lower(); aRefIndex <= aRefs->Upper(); ++aRefIndex)
1625       if (aPrevFeatureLabel == aRefs->Value(aRefIndex)) {
1626         if (aRefIndex == aRefs->Lower())
1627           aPrevFeatureLabel.Nullify();
1628         else
1629           aPrevFeatureLabel = aRefs->Value(aRefIndex - 1);
1630         break;
1631       }
1632
1633     // move the folder in the list of references before the first feature
1634     RemoveFromRefArray(aFeaturesLab, aFolderLabel);
1635     AddToRefArray(aFeaturesLab, aFolderLabel, aPrevFeatureLabel);
1636     // update first feature of the folder
1637     initFirstAttr = true;
1638   } else {
1639     // update last feature of the folder
1640     initLastAttr = true;
1641   }
1642
1643   if (initFirstAttr)
1644     aFirstFeatAttr->setValue(theFeatures.front());
1645   if (initLastAttr)
1646     aLastFeatAttr->setValue(theFeatures.back());
1647
1648   updateHistory(ModelAPI_Feature::group());
1649   return true;
1650 }
1651
1652 static FolderPtr isExtractionCorrect(const FolderPtr& theFirstFeatureFolder,
1653                                      const FolderPtr& theLastFeatureFolder,
1654                                      bool& isExtractBefore)
1655 {
1656   if (theFirstFeatureFolder.get()) {
1657     if (theLastFeatureFolder.get())
1658       return theFirstFeatureFolder == theLastFeatureFolder ? theFirstFeatureFolder : FolderPtr();
1659     else
1660       isExtractBefore = true;
1661     return theFirstFeatureFolder;
1662   } else if (theLastFeatureFolder.get()) {
1663     isExtractBefore = false;
1664     return theLastFeatureFolder;
1665   }
1666   // no folder found
1667   return FolderPtr();
1668 }
1669
1670 bool Model_Objects::removeFromFolder(
1671       const std::list<std::shared_ptr<ModelAPI_Feature> >& theFeatures,
1672       const bool theBefore)
1673 {
1674   if (theFeatures.empty())
1675     return false;
1676
1677   FolderPtr aFirstFeatureFolder =
1678       inFolder(theFeatures.front(), ModelAPI_Folder::FIRST_FEATURE_ID());
1679   FolderPtr aLastFeatureFolder =
1680       inFolder(theFeatures.back(),  ModelAPI_Folder::LAST_FEATURE_ID());
1681
1682   bool isExtractBeforeFolder = theBefore;
1683   FolderPtr aFoundFolder =
1684       isExtractionCorrect(aFirstFeatureFolder, aLastFeatureFolder, isExtractBeforeFolder);
1685   if (!aFoundFolder)
1686     return false; // list of features cannot be extracted
1687
1688   // references of the current folder
1689   ObjectPtr aFolderStartFeature;
1690   ObjectPtr aFolderEndFeature;
1691   if (aFirstFeatureFolder != aLastFeatureFolder) {
1692     aFolderStartFeature = aFoundFolder->reference(ModelAPI_Folder::FIRST_FEATURE_ID())->value();
1693     aFolderEndFeature   = aFoundFolder->reference(ModelAPI_Folder::LAST_FEATURE_ID())->value();
1694   }
1695
1696   FeaturePtr aFeatureToFind = isExtractBeforeFolder ? theFeatures.back() : theFeatures.front();
1697   std::shared_ptr<Model_Data> aData =
1698       std::static_pointer_cast<Model_Data>(aFeatureToFind->data());
1699   if (!aData || !aData->isValid())
1700     return false;
1701   TDF_Label aLabelToFind = aData->label().Father();
1702
1703   // search the label in the list of references
1704   TDF_Label aFeaturesLab = featuresLabel();
1705   Handle(TDataStd_ReferenceArray) aRefs;
1706   if (!aFeaturesLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
1707     return false; // no reference array (something is wrong)
1708   int aRefIndex = aRefs->Lower();
1709   for (; aRefIndex <= aRefs->Upper(); ++aRefIndex)
1710     if (aRefs->Value(aRefIndex) == aLabelToFind)
1711       break;
1712
1713   // update folder position
1714   if (isExtractBeforeFolder) {
1715     aData = std::dynamic_pointer_cast<Model_Data>(aFoundFolder->data());
1716     TDF_Label aFolderLabel = aData->label().Father();
1717     TDF_Label aPrevFeatureLabel = aRefs->Value(aRefIndex);
1718     // update start reference of the folder
1719     if (aFolderStartFeature.get()) {
1720       FeaturePtr aNewStartFeature;
1721       do { // skip all features placed in the composite features
1722         aPrevFeatureLabel = aRefs->Value(aRefIndex++);
1723         aNewStartFeature =
1724             aRefIndex <= aRefs->Upper() ? feature(aRefs->Value(aRefIndex)) : FeaturePtr();
1725       } while (aNewStartFeature && isSkippedFeature(aNewStartFeature));
1726       aFolderStartFeature = aNewStartFeature;
1727     }
1728     // move the folder in the list of references after the last feature from the list
1729     RemoveFromRefArray(aFeaturesLab, aFolderLabel);
1730     AddToRefArray(aFeaturesLab, aFolderLabel, aPrevFeatureLabel);
1731   } else {
1732     // update end reference of the folder
1733     if (aFolderEndFeature.get()) {
1734       FeaturePtr aNewEndFeature;
1735       do { // skip all features placed in the composite features
1736         --aRefIndex;
1737         aNewEndFeature =
1738             aRefIndex >= aRefs->Lower() ? feature(aRefs->Value(aRefIndex)) : FeaturePtr();
1739       } while (aNewEndFeature && isSkippedFeature(aNewEndFeature));
1740       aFolderEndFeature = aNewEndFeature;
1741     }
1742   }
1743
1744   // update folder references
1745   aFoundFolder->reference(ModelAPI_Folder::FIRST_FEATURE_ID())->setValue(aFolderStartFeature);
1746   aFoundFolder->reference(ModelAPI_Folder::LAST_FEATURE_ID())->setValue(aFolderEndFeature);
1747
1748   updateHistory(ModelAPI_Feature::group());
1749   return true;
1750 }
1751
1752 FolderPtr Model_Objects::findContainingFolder(const FeaturePtr& theFeature, int& theIndexInFolder)
1753 {
1754   // search the label in the list of references
1755   TDF_Label aFeaturesLab = featuresLabel();
1756   Handle(TDataStd_ReferenceArray) aRefs;
1757   if (!aFeaturesLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
1758     return FolderPtr(); // no reference array (something is wrong)
1759
1760   std::shared_ptr<Model_Data> aData =
1761       std::static_pointer_cast<Model_Data>(theFeature->data());
1762   if (!aData || !aData->isValid())
1763     return FolderPtr();
1764   TDF_Label aLabelToFind = aData->label().Father();
1765
1766   theIndexInFolder = -1;
1767   FolderPtr aFoundFolder;
1768   TDF_Label aLastFeatureLabel;
1769
1770   for (int aRefIndex = aRefs->Lower(); aRefIndex <= aRefs->Upper(); ++aRefIndex) {
1771     TDF_Label aCurLabel = aRefs->Value(aRefIndex);
1772
1773     if (aFoundFolder)
1774       ++theIndexInFolder;
1775
1776     if (aCurLabel == aLabelToFind) { // the feature is reached
1777       if (aFoundFolder) {
1778         if (isSkippedFeature(theFeature)) {
1779           theIndexInFolder = -1;
1780           return FolderPtr();
1781         }
1782         // decrease the index of the feature in the folder by the number of skipped features
1783         for (int anIndex = theIndexInFolder - 1; anIndex > 0; anIndex--) {
1784           aCurLabel = aRefs->Value(aRefIndex - anIndex);
1785           if (isSkippedFeature(feature(aCurLabel)))
1786             theIndexInFolder--;
1787         }
1788       }
1789       return aFoundFolder;
1790     }
1791
1792     if (!aFoundFolder) {
1793       // if the current label refers to a folder, feel all necessary data
1794       const ObjectPtr& aFolderObj = folder(aCurLabel);
1795       if (aFolderObj.get()) {
1796         aFoundFolder = std::dynamic_pointer_cast<ModelAPI_Folder>(aFolderObj);
1797         theIndexInFolder = -1;
1798
1799         AttributeReferencePtr aLastRef =
1800             aFoundFolder->reference(ModelAPI_Folder::LAST_FEATURE_ID());
1801         if (aLastRef->value()) {
1802           aData = std::static_pointer_cast<Model_Data>(aLastRef->value()->data());
1803           if (aData && aData->isValid())
1804             aLastFeatureLabel = aData->label().Father();
1805         } else // folder is empty
1806           aFoundFolder = FolderPtr();
1807       }
1808     } else if (aLastFeatureLabel == aCurLabel) {
1809       // folder is finished, clear all stored data
1810       theIndexInFolder = -1;
1811       aFoundFolder = FolderPtr();
1812     }
1813   }
1814
1815   // folder is not found
1816   theIndexInFolder = -1;
1817   return FolderPtr();
1818 }
1819
1820
1821 std::shared_ptr<ModelAPI_Feature> Model_Objects::feature(
1822     const std::shared_ptr<ModelAPI_Result>& theResult)
1823 {
1824   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(theResult->data());
1825   if (aData.get() && aData->isValid()) {
1826     TDF_Label aFeatureLab = aData->label().Father().Father().Father();
1827     FeaturePtr aFeature = feature(aFeatureLab);
1828     while(!aFeature.get() && aFeatureLab.Depth() > 1) { // this may be sub-result of result
1829       aFeatureLab = aFeatureLab.Father().Father();
1830       aFeature = feature(aFeatureLab);
1831     }
1832     return aFeature;
1833   }
1834   return FeaturePtr();
1835 }
1836
1837 std::string Model_Objects::featureResultGroup(FeaturePtr theFeature)
1838 {
1839   if (theFeature->data()->isValid()) {
1840     TDF_ChildIterator aLabIter(resultLabel(theFeature->data(), 0).Father());
1841     if (aLabIter.More()) {
1842       TDF_Label anArgLab = aLabIter.Value();
1843       Handle(TDataStd_Comment) aGroup;
1844       if (anArgLab.FindAttribute(TDataStd_Comment::GetID(), aGroup)) {
1845         return TCollection_AsciiString(aGroup->Get()).ToCString();
1846       }
1847     }
1848   }
1849   static std::string anEmpty;
1850   return anEmpty; // not found
1851 }
1852
1853 void Model_Objects::updateResults(FeaturePtr theFeature, std::set<FeaturePtr>& theProcessed)
1854 {
1855   if (theProcessed.find(theFeature) != theProcessed.end())
1856     return;
1857   theProcessed.insert(theFeature);
1858   // for composites update subs recursively (sketch elements results are needed for the sketch)
1859   CompositeFeaturePtr aComp = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theFeature);
1860   if (aComp.get() && aComp->getKind() != "Part") { // don't go inside of parts sub-features
1861     // update subs of composites first
1862     int aSubNum = aComp->numberOfSubs();
1863     for(int a = 0; a < aSubNum; a++) {
1864       FeaturePtr aSub = aComp->subFeature(a);
1865       updateResults(aComp->subFeature(a), theProcessed);
1866     }
1867   }
1868
1869   // it may be on undo
1870   if (!theFeature->data() || !theFeature->data()->isValid() || theFeature->isDisabled())
1871     return;
1872
1873   // check the existing results and remove them if there is nothing on the label
1874   std::list<ResultPtr>::const_iterator aResIter = theFeature->results().cbegin();
1875   while(aResIter != theFeature->results().cend()) {
1876     ResultPtr aBody = std::dynamic_pointer_cast<ModelAPI_Result>(*aResIter);
1877     if (aBody.get()) {
1878       std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(aBody->data());
1879       if (!aData.get() || !aData->isValid() || (!aBody->isDisabled() && aData->isDeleted())) {
1880         // found a disappeared result => remove it
1881         theFeature->eraseResultFromList(aBody);
1882         // start iterate from beginning because iterator is corrupted by removing
1883         aResIter = theFeature->results().cbegin();
1884         continue;
1885       }
1886     }
1887     aResIter++;
1888   }
1889   // check that results are presented on all labels
1890   int aResSize = int(theFeature->results().size());
1891   TDF_ChildIterator aLabIter(resultLabel(theFeature->data(), 0).Father());
1892   for(; aLabIter.More(); aLabIter.Next()) {
1893     // here must be GUID of the feature
1894     int aResIndex = aLabIter.Value().Tag() - 1;
1895     ResultPtr aNewBody;
1896     if (aResSize <= aResIndex) {
1897       TDF_Label anArgLab = aLabIter.Value();
1898       Handle(TDataStd_Comment) aGroup;
1899       if (anArgLab.FindAttribute(TDataStd_Comment::GetID(), aGroup)) {
1900         if (aGroup->Get() == ModelAPI_ResultBody::group().c_str()) {
1901           aNewBody = createBody(theFeature->data(), aResIndex);
1902         } else if (aGroup->Get() == ModelAPI_ResultPart::group().c_str()) {
1903           if (aResIndex <= (int)theFeature->results().size()) {// to avoid crash if previous execute
1904             // for index = 0 erases result
1905             std::shared_ptr<ModelAPI_ResultPart> aNewP = createPart(theFeature->data(), aResIndex);
1906             if (!aNewP->data()->isDeleted()) {
1907               theFeature->setResult(aNewP, aResIndex);
1908               if (!aNewP->partDoc().get())
1909                 // create the part result: it is better to restore the previous result if possible
1910                 theFeature->execute();
1911             }
1912           }
1913         } else if (aGroup->Get() == ModelAPI_ResultConstruction::group().c_str()) {
1914           ResultConstructionPtr aConstr = createConstruction(theFeature->data(), aResIndex);
1915           if (!aConstr->data()->isDeleted()) {
1916             if (!aConstr->updateShape())
1917               theFeature->execute(); // not stored shape in the data structure, execute to have it
1918             else
1919               theFeature->setResult(aConstr, aResIndex); // result is ready without execution
1920           }
1921         } else if (aGroup->Get() == ModelAPI_ResultGroup::group().c_str()) {
1922           aNewBody = createGroup(theFeature->data(), aResIndex);
1923         } else if (aGroup->Get() == ModelAPI_ResultField::group().c_str()) {
1924           ResultFieldPtr aField = createField(theFeature->data(), aResIndex);
1925           aField->updateSteps(); // to refresh the internal data
1926           aNewBody = aField;
1927         } else if (aGroup->Get() == ModelAPI_ResultParameter::group().c_str()) {
1928           theFeature->attributeChanged("expression"); // just produce a value
1929         } else {
1930           Events_InfoMessage("Model_Objects", "Unknown type of result is found in the document:")
1931             .arg(TCollection_AsciiString(aGroup->Get()).ToCString()).send();
1932         }
1933       }
1934       if (aNewBody && !aNewBody->data()->isDeleted()) {
1935         theFeature->setResult(aNewBody, aResIndex);
1936       }
1937     }
1938   }
1939   if (aResSize > 0) { // check there exist a body that must be updated
1940     std::list<ResultPtr>::const_iterator aRes = theFeature->results().cbegin();
1941     for (; aResSize && aRes != theFeature->results().cend(); aRes++, aResSize++) {
1942       if ((*aRes)->data()->isValid()) {
1943         if ((*aRes)->groupName() == ModelAPI_ResultBody::group()) {
1944           ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(*aRes);
1945           aBody->updateSubs(aBody->shape(), false);
1946         } else if ((*aRes)->groupName() == ModelAPI_ResultConstruction::group()) {
1947           // update the cashed myShape presented in construction
1948           ResultConstructionPtr aConstr =
1949             std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
1950           aConstr->updateShape();
1951         }
1952       }
1953     }
1954   }
1955 }
1956
1957 ResultPtr Model_Objects::findByName(const std::wstring theName)
1958 {
1959   ResultPtr aResult;
1960   FeaturePtr aResFeature; // keep feature to return the latest one
1961   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator anObjIter(myFeatures);
1962   for(; anObjIter.More(); anObjIter.Next()) {
1963     FeaturePtr& aFeature = anObjIter.ChangeValue();
1964     if (!aFeature.get() || aFeature->isDisabled()) // may be on close
1965       continue;
1966     std::list<ResultPtr> allResults;
1967     ModelAPI_Tools::allResults(aFeature, allResults);
1968     std::list<ResultPtr>::iterator aRIter = allResults.begin();
1969     for (; aRIter != allResults.cend(); aRIter++) {
1970       ResultPtr aRes = *aRIter;
1971       if (aRes.get() && aRes->data() && aRes->data()->isValid() && !aRes->isDisabled() &&
1972           aRes->data()->name() == theName)
1973       {
1974         if (!aResult.get() || isLater(aFeature, aResFeature)) { // select the latest
1975           aResult = aRes;
1976           aResFeature = aFeature;
1977         }
1978       }
1979     }
1980   }
1981   return aResult;
1982 }
1983
1984 TDF_Label Model_Objects::nextLabel(TDF_Label theCurrent, int& theIndex, const bool theReverse)
1985 {
1986   Handle(TDataStd_ReferenceArray) aRefs;
1987   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
1988     int aStart = theIndex == kUNDEFINED_FEATURE_INDEX ? aRefs->Lower() : theIndex;
1989     for(int a = aStart; a <= aRefs->Upper(); a++) { // iterate all existing features
1990       TDF_Label aCurLab = aRefs->Value(a);
1991       if (aCurLab.IsEqual(theCurrent)) {
1992         a += theReverse ? -1 : 1;
1993         if (a >= aRefs->Lower() && a <= aRefs->Upper()) {
1994           theIndex = a;
1995           return aRefs->Value(a);
1996         }
1997         break; // finish iteration: it's last feature
1998       }
1999     }
2000   }
2001   return TDF_Label();
2002 }
2003
2004 FeaturePtr Model_Objects::nextFeature(FeaturePtr theCurrent, int& theIndex, const bool theReverse)
2005 {
2006   std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theCurrent->data());
2007   if (aData.get() && aData->isValid()) {
2008     TDF_Label aFeatureLabel = aData->label().Father();
2009     do {
2010       TDF_Label aNextLabel = nextLabel(aFeatureLabel, theIndex, theReverse);
2011       if (aNextLabel.IsNull())
2012         break; // the last or something is wrong
2013       FeaturePtr aFound = feature(aNextLabel);
2014       if (aFound)
2015         return aFound; // the feature is found
2016       // if the next label is a folder, skip it
2017       aFeatureLabel = folder(aNextLabel).get() ? aNextLabel : TDF_Label();
2018     } while (!aFeatureLabel.IsNull());
2019   }
2020   return FeaturePtr(); // not found, last, or something is wrong
2021 }
2022
2023 FeaturePtr Model_Objects::firstFeature()
2024 {
2025   Handle(TDataStd_ReferenceArray) aRefs;
2026   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
2027     return feature(aRefs->Value(aRefs->Lower()));
2028   }
2029   return FeaturePtr(); // no features at all
2030 }
2031
2032 FeaturePtr Model_Objects::lastFeature()
2033 {
2034   Handle(TDataStd_ReferenceArray) aRefs;
2035   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
2036     // comment this because of #2674 - features are removed from array on deactivation of Part
2037     /*FeaturePtr aLast = feature(aRefs->Value(aRefs->Upper()));
2038     if (!aLast.get() && aRefs->Length() != 0) { // erase the invalid feature from the array
2039       RemoveFromRefArray(featuresLabel(), aRefs->Value(aRefs->Upper()));
2040       return lastFeature(); // try once again, after the last was removed
2041     }*/
2042     return feature(aRefs->Value(aRefs->Upper()));
2043   }
2044   return FeaturePtr(); // no features at all
2045 }
2046
2047 bool Model_Objects::isLater(FeaturePtr theLater, FeaturePtr theCurrent) const
2048 {
2049   if (theLater->getKind() == "InternalSelectionInPartFeature")
2050     return true;
2051   std::shared_ptr<Model_Data> aLaterD = std::static_pointer_cast<Model_Data>(theLater->data());
2052   std::shared_ptr<Model_Data> aCurrentD = std::static_pointer_cast<Model_Data>(theCurrent->data());
2053   if (aLaterD.get() && aLaterD->isValid() && aCurrentD.get() && aCurrentD->isValid()) {
2054     TDF_Label aLaterL = aLaterD->label().Father();
2055     TDF_Label aCurrentL = aCurrentD->label().Father();
2056     int aLaterI = -1, aCurentI = -1; // not found yet state
2057     Handle(TDataStd_ReferenceArray) aRefs;
2058     if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
2059       for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) { // iterate all existing features
2060         TDF_Label aCurLab = aRefs->Value(a);
2061         if (aCurLab.IsEqual(aLaterL)) {
2062           aLaterI = a;
2063         } else if (aCurLab.IsEqual(aCurrentL)) {
2064           aCurentI = a;
2065         } else continue;
2066         if (aLaterI != -1 && aCurentI != -1) // both are found
2067           return aLaterI > aCurentI;
2068       }
2069     }
2070   }
2071   return false; // not found, or something is wrong
2072 }
2073
2074 std::list<std::shared_ptr<ModelAPI_Object> > Model_Objects::allObjects()
2075 {
2076   std::list<std::shared_ptr<ModelAPI_Object> > aResult;
2077   Handle(TDataStd_ReferenceArray) aRefs;
2078   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
2079     for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
2080       ObjectPtr anObject = object(aRefs->Value(a));
2081       if (!anObject.get()) // is it a folder?
2082         anObject = folder(aRefs->Value(a));
2083       if (anObject.get())
2084         aResult.push_back(anObject);
2085     }
2086   }
2087   return aResult;
2088 }
2089
2090 std::list<std::shared_ptr<ModelAPI_Feature> > Model_Objects::allFeatures()
2091 {
2092   std::list<std::shared_ptr<ModelAPI_Feature> > aResult;
2093   Handle(TDataStd_ReferenceArray) aRefs;
2094   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
2095     for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
2096       FeaturePtr aFeature = feature(aRefs->Value(a));
2097       if (aFeature.get())
2098         aResult.push_back(aFeature);
2099     }
2100   }
2101   return aResult;
2102 }
2103
2104 int Model_Objects::numInternalFeatures()
2105 {
2106   Handle(TDataStd_ReferenceArray) aRefs;
2107   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
2108     return aRefs->Upper() - aRefs->Lower() + 1;
2109   }
2110   return 0; // invalid
2111 }
2112
2113 std::shared_ptr<ModelAPI_Feature> Model_Objects::internalFeature(const int theIndex)
2114 {
2115   Handle(TDataStd_ReferenceArray) aRefs;
2116   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
2117     return feature(aRefs->Value(aRefs->Lower() + theIndex));
2118   }
2119   return FeaturePtr(); // invalid
2120 }
2121
2122 #if OCC_VERSION_LARGE < 0x07080000
2123 Standard_Integer HashCode(const TDF_Label& theLab, const Standard_Integer theUpper)
2124 {
2125   return TDF_LabelMapHasher::HashCode(theLab, theUpper);
2126 }
2127 Standard_Boolean IsEqual(const TDF_Label& theLab1, const TDF_Label& theLab2)
2128 {
2129   return TDF_LabelMapHasher::IsEqual(theLab1, theLab2);
2130 }
2131 #endif