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