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