]> SALOME platform Git repositories - modules/shaper.git/blob - src/Model/Model_Objects.cpp
Salome HOME
Merge remote-tracking branch 'origin/DISPLAY_FIELD_STEP'
[modules/shaper.git] / src / Model / Model_Objects.cpp
1 // Copyright (C) 2014-2019  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 email : webmaster.salome@opencascade.com
18 //
19
20 #include <Model_Objects.h>
21 #include <Model_Data.h>
22 #include <Model_Document.h>
23 #include <Model_Events.h>
24 #include <Model_Session.h>
25 #include <Model_ResultPart.h>
26 #include <Model_ResultConstruction.h>
27 #include <Model_ResultBody.h>
28 #include <Model_ResultGroup.h>
29 #include <Model_ResultField.h>
30 #include <Model_ResultParameter.h>
31 #include <Model_AttributeRefList.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 void Model_Objects::synchronizeFeatures(
802   const TDF_LabelList& theUpdated, const bool theUpdateReferences,
803   const bool theExecuteFeatures, const bool theOpen, const bool theFlush)
804 {
805   Model_Document* anOwner = std::dynamic_pointer_cast<Model_Document>(myDoc).get();
806   if (!anOwner) // this may happen on creation of document: nothing there, so nothing to synchronize
807     return;
808   // after all updates, sends a message that groups of features were created or updated
809   Events_Loop* aLoop = Events_Loop::loop();
810   static Events_ID aDispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
811   static Events_ID aCreateEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
812   static Events_ID anUpdateEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
813   static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
814   static Events_ID aDeleteEvent = Events_Loop::eventByName(EVENT_OBJECT_DELETED);
815   static Events_ID aToHideEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
816   bool isActive = aLoop->activateFlushes(false);
817
818   // collect all updated labels map
819   TDF_LabelMap anUpdatedMap;
820   TDF_ListIteratorOfLabelList anUpdatedIter(theUpdated);
821   for(; anUpdatedIter.More(); anUpdatedIter.Next()) {
822     TDF_Label& aFeatureLab = anUpdatedIter.Value();
823     while(aFeatureLab.Depth() > 3)
824       aFeatureLab = aFeatureLab.Father();
825     if (myFeatures.IsBound(aFeatureLab) || myFolders.IsBound(aFeatureLab))
826       anUpdatedMap.Add(aFeatureLab);
827   }
828
829   // update all objects by checking are they on labels or not
830   std::set<ObjectPtr> aNewFeatures, aKeptFeatures;
831   TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
832   for (; aLabIter.More(); aLabIter.Next()) {
833     TDF_Label aFeatureLabel = aLabIter.Value()->Label();
834     if (!myFeatures.IsBound(aFeatureLabel) && !myFolders.IsBound(aFeatureLabel)) {
835       // a new feature or folder is inserted
836
837       std::string aFeatureID = TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(
838                                aLabIter.Value())->Get()).ToCString();
839       bool isFolder = aFeatureID == ModelAPI_Folder::ID();
840
841       std::shared_ptr<Model_Session> aSession =
842           std::dynamic_pointer_cast<Model_Session>(ModelAPI_Session::get());
843
844       // create a feature
845       ObjectPtr aFeature = isFolder ? ObjectPtr(new ModelAPI_Folder)
846                                     : ObjectPtr(aSession->createFeature(aFeatureID, anOwner));
847       if (!aFeature.get()) {
848         // something is wrong, most probably, the opened document has invalid structure
849         Events_InfoMessage("Model_Objects", "Invalid type of object in the document").send();
850         aLabIter.Value()->Label().ForgetAllAttributes();
851         continue;
852       }
853       aFeature->init();
854       // this must be before "setData" to redo the sketch line correctly
855       if (isFolder)
856         myFolders.Bind(aFeatureLabel, aFeature);
857       else
858         myFeatures.Bind(aFeatureLabel, std::dynamic_pointer_cast<ModelAPI_Feature>(aFeature));
859       aNewFeatures.insert(aFeature);
860       initData(aFeature, aFeatureLabel, TAG_FEATURE_ARGUMENTS);
861       updateHistory(aFeature);
862
863       // event: model is updated
864       ModelAPI_EventCreator::get()->sendUpdated(aFeature, aCreateEvent);
865     } else {  // nothing is changed, both iterators are incremented
866       ObjectPtr anObject;
867       FeaturePtr aFeature;
868       if (myFeatures.Find(aFeatureLabel, aFeature)) {
869         aKeptFeatures.insert(aFeature);
870         anObject = aFeature;
871       } else
872         if (myFolders.Find(aFeatureLabel, anObject))
873           aKeptFeatures.insert(anObject);
874
875       if (anUpdatedMap.Contains(aFeatureLabel)) {
876         if (!theOpen) { // on abort/undo/redo reinitialize attributes if something is changed
877           std::list<std::shared_ptr<ModelAPI_Attribute> > anAttrs =
878             anObject->data()->attributes("");
879           std::list<std::shared_ptr<ModelAPI_Attribute> >::iterator anAttr = anAttrs.begin();
880           for(; anAttr != anAttrs.end(); anAttr++)
881             (*anAttr)->reinit();
882         }
883         ModelAPI_EventCreator::get()->sendUpdated(anObject, anUpdateEvent);
884         if (aFeature && aFeature->getKind() == "Parameter") {
885           // if parameters are changed, update the results (issue 937)
886           const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
887           std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
888           for (; aRIter != aResults.cend(); aRIter++) {
889             std::shared_ptr<ModelAPI_Result> aRes = *aRIter;
890             if (aRes->data()->isValid() && !aRes->isDisabled()) {
891               ModelAPI_EventCreator::get()->sendUpdated(aRes, anUpdateEvent);
892             }
893           }
894         }
895       }
896     }
897   }
898
899   // check all features are checked: if not => it was removed
900   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myFeatures);
901   while (aFIter.More()) {
902     if (aKeptFeatures.find(aFIter.Value()) == aKeptFeatures.end()
903       && aNewFeatures.find(aFIter.Value()) == aNewFeatures.end()) {
904         FeaturePtr aFeature = aFIter.Value();
905         // event: model is updated
906         //if (aFeature->isInHistory()) {
907         ModelAPI_EventCreator::get()->sendDeleted(myDoc, ModelAPI_Feature::group());
908         //}
909         // results of this feature must be redisplayed (hided)
910         // redisplay also removed feature (used for sketch and AISObject)
911         ModelAPI_EventCreator::get()->sendUpdated(aFeature, aRedispEvent);
912         updateHistory(aFeature);
913         aFeature->erase();
914
915         // unbind after the "erase" call: on abort sketch
916         // is removes sub-objects that corrupts aFIter
917         myFeatures.UnBind(aFIter.Key());
918         // reinitialize iterator because unbind may corrupt the previous order in the map
919         aFIter.Initialize(myFeatures);
920     } else
921       aFIter.Next();
922   }
923   // verify folders are checked: if not => is was removed
924   for (NCollection_DataMap<TDF_Label, ObjectPtr>::Iterator aFldIt(myFolders);
925        aFldIt.More(); aFldIt.Next()) {
926     ObjectPtr aCurObj = aFldIt.Value();
927     if (aKeptFeatures.find(aCurObj) == aKeptFeatures.end() &&
928         aNewFeatures.find(aCurObj) == aNewFeatures.end()) {
929       ModelAPI_EventCreator::get()->sendDeleted(myDoc, ModelAPI_Folder::group());
930       // results of this feature must be redisplayed (hided)
931       // redisplay also removed feature (used for sketch and AISObject)
932       ModelAPI_EventCreator::get()->sendUpdated(aCurObj, aRedispEvent);
933       updateHistory(aCurObj);
934       aCurObj->erase();
935
936       // unbind after the "erase" call: on abort sketch
937       // is removes sub-objects that corrupts aFIter
938       myFolders.UnBind(aFldIt.Key());
939       // reinitialize iterator because unbind may corrupt the previous order in the map
940       aFldIt.Initialize(myFolders);
941     }
942   }
943
944   if (theUpdateReferences) {
945     synchronizeBackRefs();
946   }
947   // update results of the features (after features created because
948   // they may be connected, like sketch and sub elements)
949   // After synchronization of back references because sketch
950   // must be set in sub-elements before "execute" by updateResults
951   std::set<FeaturePtr> aProcessed; // composites must be updated after their subs (issue 360)
952   TDF_ChildIDIterator aLabIter2(featuresLabel(), TDataStd_Comment::GetID());
953   for (; aLabIter2.More(); aLabIter2.Next()) {
954     TDF_Label aFeatureLabel = aLabIter2.Value()->Label();
955     if (myFeatures.IsBound(aFeatureLabel)) {  // a new feature is inserted
956       FeaturePtr aFeature = myFeatures.Find(aFeatureLabel);
957       updateResults(aFeature, aProcessed);
958     }
959   }
960   // the synchronize should be done after updateResults
961   // in order to correct back references of updated results
962   if (theUpdateReferences) {
963     synchronizeBackRefs();
964   }
965   if (!theUpdated.IsEmpty()) {
966     // this means there is no control what was modified => remove history cash
967     myHistory.clear();
968   }
969
970   if (!theExecuteFeatures)
971     anOwner->setExecuteFeatures(false);
972   aLoop->activateFlushes(isActive);
973
974   if (theFlush) {
975     aLoop->flush(aDeleteEvent);
976     // delete should be emitted before create to reacts to aborted feature
977     aLoop->flush(aCreateEvent);
978     aLoop->flush(anUpdateEvent);
979     aLoop->flush(aCreateEvent); // after update of features, there could be results created
980     aLoop->flush(aDeleteEvent); // or deleted
981     aLoop->flush(aRedispEvent);
982     aLoop->flush(aToHideEvent);
983   }
984   if (!theExecuteFeatures)
985     anOwner->setExecuteFeatures(true);
986 }
987
988 /// synchronizes back references for the given object basing on the collected data
989 void Model_Objects::synchronizeBackRefsForObject(const std::set<AttributePtr>& theNewRefs,
990   ObjectPtr theObject)
991 {
992   if (!theObject.get() || !theObject->data()->isValid())
993     return; // invalid
994   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(theObject->data());
995   // iterate new list to compare with current
996   std::set<AttributePtr>::iterator aNewIter = theNewRefs.begin();
997   for(; aNewIter != theNewRefs.end(); aNewIter++) {
998     // for the Model_AttributeRefList erase cash (issue #2819)
999     std::shared_ptr<Model_AttributeRefList> aRefList =
1000       std::dynamic_pointer_cast<Model_AttributeRefList>(*aNewIter);
1001     if (aRefList)
1002       aRefList->eraseHash();
1003
1004     if (aData->refsToMe().find(*aNewIter) == aData->refsToMe().end()) {
1005       FeaturePtr aRefFeat = std::dynamic_pointer_cast<ModelAPI_Feature>((*aNewIter)->owner());
1006       if (aRefFeat)
1007         aData->addBackReference(aRefFeat, (*aNewIter)->id());
1008       else // add back reference to a folder
1009         aData->addBackReference((*aNewIter)->owner(), (*aNewIter)->id());
1010     }
1011   }
1012   if (theNewRefs.size() != aData->refsToMe().size()) { // some back ref must be removed
1013     std::set<AttributePtr>::iterator aCurrentIter = aData->refsToMe().begin();
1014     while(aCurrentIter != aData->refsToMe().end()) {
1015       if (theNewRefs.find(*aCurrentIter) == theNewRefs.end()) {
1016         // for external references from other documents this system
1017         // is not working: refs are collected from
1018         // different Model_Objects, so before remove check this
1019         // external object exists and still referenced
1020         bool aLeaveIt = false;
1021         if ((*aCurrentIter)->owner().get() && (*aCurrentIter)->owner()->document() != myDoc &&
1022             (*aCurrentIter)->owner()->data().get() && (*aCurrentIter)->owner()->data()->isValid()) {
1023           std::list<std::pair<std::string, std::list<std::shared_ptr<ModelAPI_Object> > > > aRefs;
1024           (*aCurrentIter)->owner()->data()->referencesToObjects(aRefs);
1025           std::list<std::pair<std::string, std::list<std::shared_ptr<ModelAPI_Object> >>>::iterator
1026             aRefIter = aRefs.begin();
1027           for(; aRefIter != aRefs.end(); aRefIter++) {
1028             if ((*aCurrentIter)->id() == aRefIter->first) {
1029               std::list<std::shared_ptr<ModelAPI_Object> >::iterator anOIt;
1030               for(anOIt = aRefIter->second.begin(); anOIt != aRefIter->second.end(); anOIt++) {
1031                 if (*anOIt == theObject) {
1032                   aLeaveIt = true;
1033                 }
1034               }
1035             }
1036           }
1037         }
1038         if (!aLeaveIt) {
1039           aData->removeBackReference(*aCurrentIter);
1040           aCurrentIter = aData->refsToMe().begin(); // reinitialize iteration after delete
1041         } else aCurrentIter++;
1042       } else aCurrentIter++;
1043     }
1044   }
1045   // for the last feature in the folder, check if it is a sub-feature,
1046   // then refer the folder to a top-level parent composite feature
1047   const std::set<AttributePtr>& aRefs = aData->refsToMe();
1048   std::set<AttributePtr>::iterator anIt = aRefs.begin();
1049   for (; anIt != aRefs.end(); ++anIt)
1050     if ((*anIt)->id() == ModelAPI_Folder::LAST_FEATURE_ID())
1051       break;
1052   if (anIt != aRefs.end()) {
1053     FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
1054     if (aFeature) {
1055       CompositeFeaturePtr aParent;
1056       CompositeFeaturePtr aGrandParent = ModelAPI_Tools::compositeOwner(aFeature);
1057       do {
1058         aParent = aGrandParent;
1059         if (aGrandParent)
1060           aGrandParent = ModelAPI_Tools::compositeOwner(aParent);
1061       } while (aGrandParent.get());
1062       if (aParent) {
1063         ObjectPtr aFolder = (*anIt)->owner();
1064         // remove reference from the current feature
1065         aData->removeBackReference(aFolder, ModelAPI_Folder::LAST_FEATURE_ID());
1066         // set reference to a top-level parent
1067         aFolder->data()->reference(ModelAPI_Folder::LAST_FEATURE_ID())->setValue(aParent);
1068         std::shared_ptr<Model_Data> aParentData =
1069             std::dynamic_pointer_cast<Model_Data>(aParent->data());
1070         aParentData->addBackReference(aFolder, ModelAPI_Folder::LAST_FEATURE_ID());
1071       }
1072     }
1073   }
1074   aData->updateConcealmentFlag();
1075 }
1076
1077 static void collectReferences(std::shared_ptr<ModelAPI_Data> theData,
1078                               std::map<ObjectPtr, std::set<AttributePtr> >& theRefs)
1079 {
1080   if (theData.get()) {
1081     std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
1082     theData->referencesToObjects(aRefs);
1083     std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator aRefsIt = aRefs.begin();
1084     for(; aRefsIt != aRefs.end(); aRefsIt++) {
1085       std::list<ObjectPtr>::iterator aRefTo = aRefsIt->second.begin();
1086       for(; aRefTo != aRefsIt->second.end(); aRefTo++) {
1087         if (*aRefTo) {
1088           std::map<ObjectPtr, std::set<AttributePtr> >::iterator aFound = theRefs.find(*aRefTo);
1089           if (aFound == theRefs.end()) {
1090             theRefs[*aRefTo] = std::set<AttributePtr>();
1091             aFound = theRefs.find(*aRefTo);
1092           }
1093           aFound->second.insert(theData->attribute(aRefsIt->first));
1094         }
1095       }
1096     }
1097   }
1098 }
1099
1100 void Model_Objects::synchronizeBackRefs()
1101 {
1102   // collect all back references in the separated container: to update everything at once,
1103   // without additional Concealment switching on and off: only the final modification
1104
1105   // referenced (slave) objects to referencing attributes
1106   std::map<ObjectPtr, std::set<AttributePtr> > allRefs;
1107   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFeatures(myFeatures);
1108   for(; aFeatures.More(); aFeatures.Next()) {
1109     FeaturePtr aFeature = aFeatures.Value();
1110     collectReferences(aFeature->data(), allRefs);
1111   }
1112   NCollection_DataMap<TDF_Label, ObjectPtr>::Iterator aFolders(myFolders);
1113   for(; aFolders.More(); aFolders.Next()) {
1114     ObjectPtr aFolder = aFolders.Value();
1115     collectReferences(aFolder->data(), allRefs);
1116   }
1117   // second iteration: just compare back-references with existing in features and results
1118   for(aFeatures.Initialize(myFeatures); aFeatures.More(); aFeatures.Next()) {
1119     FeaturePtr aFeature = aFeatures.Value();
1120     static std::set<AttributePtr> anEmpty;
1121     std::map<ObjectPtr, std::set<AttributePtr> >::iterator aFound = allRefs.find(aFeature);
1122     if (aFound == allRefs.end()) { // not found => erase all back references
1123       synchronizeBackRefsForObject(anEmpty, aFeature);
1124     } else {
1125       synchronizeBackRefsForObject(aFound->second, aFeature);
1126       allRefs.erase(aFound); // to check that all refs are counted
1127     }
1128     // also for results
1129     std::list<ResultPtr> aResults;
1130     ModelAPI_Tools::allResults(aFeature, aResults);
1131     std::list<ResultPtr>::iterator aRIter = aResults.begin();
1132     for(; aRIter != aResults.cend(); aRIter++) {
1133       aFound = allRefs.find(*aRIter);
1134       if (aFound == allRefs.end()) { // not found => erase all back references
1135         synchronizeBackRefsForObject(anEmpty, *aRIter);
1136       } else {
1137         synchronizeBackRefsForObject(aFound->second, *aRIter);
1138         allRefs.erase(aFound); // to check that all refs are counted
1139       }
1140     }
1141   }
1142   for(aFeatures.Initialize(myFeatures); aFeatures.More(); aFeatures.Next()) {
1143     FeaturePtr aFeature = aFeatures.Value();
1144     std::list<ResultPtr> aResults;
1145     ModelAPI_Tools::allResults(aFeature, aResults);
1146     // update the concealment status for display in isConcealed of ResultBody
1147     std::list<ResultPtr>::iterator aRIter = aResults.begin();
1148     for(; aRIter != aResults.cend(); aRIter++) {
1149       (*aRIter)->isConcealed();
1150     }
1151   }
1152   // the rest all refs means that feature references to the external document feature:
1153   // process also them
1154   std::map<ObjectPtr, std::set<AttributePtr> >::iterator anExtIter = allRefs.begin();
1155   for(; anExtIter != allRefs.end(); anExtIter++) {
1156     synchronizeBackRefsForObject(anExtIter->second, anExtIter->first);
1157   }
1158 }
1159
1160 TDF_Label Model_Objects::resultLabel(
1161   const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theResultIndex)
1162 {
1163   const std::shared_ptr<Model_Data>& aData =
1164     std::dynamic_pointer_cast<Model_Data>(theFeatureData);
1165   return aData->label().Father().FindChild(TAG_FEATURE_RESULTS).FindChild(theResultIndex + 1);
1166 }
1167
1168 bool Model_Objects::hasCustomName(DataPtr theFeatureData,
1169                                   ResultPtr theResult,
1170                                   int theResultIndex,
1171                                   std::string& theParentName) const
1172 {
1173   ResultBodyPtr aBodyRes = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theFeatureData->owner());
1174   if (aBodyRes) {
1175     // only for top-results (works for the cases when results are not yet added to the feature)
1176     FeaturePtr anOwner = ModelAPI_Feature::feature(theResult);
1177
1178     // names of sub-solids in CompSolid should be default (for example,
1179     // result of boolean operation 'Boolean_1' is a CompSolid which is renamed to 'MyBOOL',
1180     // however, sub-elements of 'MyBOOL' should be named 'Boolean_1_1', 'Boolean_1_2' etc.)
1181     if (std::dynamic_pointer_cast<Model_Data>(aBodyRes->data())->label().Depth() == 6) {
1182       std::ostringstream aDefaultName;
1183       // compute default name of CompSolid (name of feature + index of CompSolid's result)
1184       int aBodyResultIndex = 0;
1185       const std::list<ResultPtr>& aResults = anOwner->results();
1186       std::list<ResultPtr>::const_iterator anIt = aResults.begin();
1187       for (; anIt != aResults.end(); ++anIt, ++aBodyResultIndex)
1188         if (aBodyRes == *anIt)
1189           break;
1190       aDefaultName << anOwner->name();
1191       aDefaultName << "_" << (aBodyResultIndex + 1);
1192       theParentName = aDefaultName.str();
1193     } else { // just name of the parent result if it is deeper than just a sub-result
1194       theParentName = aBodyRes->data()->name();
1195     }
1196     return false;
1197   }
1198
1199   std::pair<std::string, bool> aName = ModelAPI_Tools::getDefaultName(theResult);
1200   if (aName.second)
1201     theParentName = aName.first;
1202   return aName.second;
1203 }
1204
1205 void Model_Objects::storeResult(std::shared_ptr<ModelAPI_Data> theFeatureData,
1206                                 std::shared_ptr<ModelAPI_Result> theResult,
1207                                 const int theResultIndex)
1208 {
1209   theResult->init();
1210   theResult->setDoc(myDoc);
1211   initData(theResult, resultLabel(theFeatureData, theResultIndex), TAG_FEATURE_ARGUMENTS);
1212   if (theResult->data()->name().empty()) {
1213     // if was not initialized, generate event and set a name
1214     std::string aNewName = theFeatureData->name();
1215     if (hasCustomName(theFeatureData, theResult, theResultIndex, aNewName)) {
1216       // if the name of result is user-defined, then, at first time, assign name of the result
1217       // by empty string to be sure that corresponding flag in the data model is set
1218       theResult->data()->setName("");
1219     } else {
1220       std::stringstream aName;
1221       aName << aNewName;
1222       // if there are several results (issue #899: any number of result),
1223       // add unique prefix starting from second
1224       if (theResultIndex > 0 || theResult->groupName() == ModelAPI_ResultBody::group())
1225         aName << "_" << theResultIndex + 1;
1226       aNewName = aName.str();
1227     }
1228     theResult->data()->setName(aNewName);
1229   }
1230 }
1231
1232 std::shared_ptr<ModelAPI_ResultConstruction> Model_Objects::createConstruction(
1233     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1234 {
1235   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1236   TDataStd_Comment::Set(aLab, ModelAPI_ResultConstruction::group().c_str());
1237   ObjectPtr anOldObject = object(aLab);
1238   std::shared_ptr<ModelAPI_ResultConstruction> aResult;
1239   if (anOldObject.get()) {
1240     aResult = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(anOldObject);
1241   }
1242   if (!aResult.get()) {
1243     aResult = std::shared_ptr<ModelAPI_ResultConstruction>(new Model_ResultConstruction);
1244     storeResult(theFeatureData, aResult, theIndex);
1245   }
1246   return aResult;
1247 }
1248
1249 std::shared_ptr<ModelAPI_ResultBody> Model_Objects::createBody(
1250     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1251 {
1252   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1253   TDataStd_Comment::Set(aLab, ModelAPI_ResultBody::group().c_str());
1254   ObjectPtr anOldObject = object(aLab);
1255   std::shared_ptr<ModelAPI_ResultBody> aResult;
1256   if (anOldObject.get()) {
1257     aResult = std::dynamic_pointer_cast<ModelAPI_ResultBody>(anOldObject);
1258   }
1259   if (!aResult.get()) {
1260     aResult = std::shared_ptr<ModelAPI_ResultBody>(new Model_ResultBody);
1261     storeResult(theFeatureData, aResult, theIndex);
1262   }
1263   return aResult;
1264 }
1265
1266 std::shared_ptr<ModelAPI_ResultPart> Model_Objects::createPart(
1267     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1268 {
1269   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1270   TDataStd_Comment::Set(aLab, ModelAPI_ResultPart::group().c_str());
1271   ObjectPtr anOldObject = object(aLab);
1272   std::shared_ptr<ModelAPI_ResultPart> aResult;
1273   if (anOldObject.get()) {
1274     aResult = std::dynamic_pointer_cast<ModelAPI_ResultPart>(anOldObject);
1275   }
1276   if (!aResult.get()) {
1277     aResult = std::shared_ptr<ModelAPI_ResultPart>(new Model_ResultPart);
1278     storeResult(theFeatureData, aResult, theIndex);
1279   }
1280   return aResult;
1281 }
1282
1283 std::shared_ptr<ModelAPI_ResultPart> Model_Objects::copyPart(
1284     const std::shared_ptr<ModelAPI_ResultPart>& theOrigin,
1285     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1286 {
1287   std::shared_ptr<ModelAPI_ResultPart> aResult = createPart(theFeatureData, theIndex);
1288   aResult->data()->reference(Model_ResultPart::BASE_REF_ID())->setValue(theOrigin);
1289   return aResult;
1290 }
1291
1292 std::shared_ptr<ModelAPI_ResultGroup> Model_Objects::createGroup(
1293     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1294 {
1295   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1296   TDataStd_Comment::Set(aLab, ModelAPI_ResultGroup::group().c_str());
1297   ObjectPtr anOldObject = object(aLab);
1298   std::shared_ptr<ModelAPI_ResultGroup> aResult;
1299   if (anOldObject.get()) {
1300     aResult = std::dynamic_pointer_cast<ModelAPI_ResultGroup>(anOldObject);
1301   }
1302   if (!aResult.get()) {
1303     aResult = std::shared_ptr<ModelAPI_ResultGroup>(new Model_ResultGroup(theFeatureData));
1304     storeResult(theFeatureData, aResult, theIndex);
1305   }
1306   return aResult;
1307 }
1308
1309 std::shared_ptr<ModelAPI_ResultField> Model_Objects::createField(
1310     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1311 {
1312   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1313   TDataStd_Comment::Set(aLab, ModelAPI_ResultField::group().c_str());
1314   ObjectPtr anOldObject = object(aLab);
1315   std::shared_ptr<ModelAPI_ResultField> aResult;
1316   if (anOldObject.get()) {
1317     aResult = std::dynamic_pointer_cast<ModelAPI_ResultField>(anOldObject);
1318   }
1319   if (!aResult.get()) {
1320     aResult = std::shared_ptr<ModelAPI_ResultField>(new Model_ResultField(theFeatureData));
1321     storeResult(theFeatureData, aResult, theIndex);
1322   }
1323   return aResult;
1324 }
1325
1326 std::shared_ptr<ModelAPI_ResultParameter> Model_Objects::createParameter(
1327       const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1328 {
1329   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1330   TDataStd_Comment::Set(aLab, ModelAPI_ResultParameter::group().c_str());
1331   ObjectPtr anOldObject = object(aLab);
1332   std::shared_ptr<ModelAPI_ResultParameter> aResult;
1333   if (anOldObject.get()) {
1334     aResult = std::dynamic_pointer_cast<ModelAPI_ResultParameter>(anOldObject);
1335   }
1336   if (!aResult.get()) {
1337     aResult = std::shared_ptr<ModelAPI_ResultParameter>(new Model_ResultParameter);
1338     storeResult(theFeatureData, aResult, theIndex);
1339   }
1340   return aResult;
1341 }
1342
1343 std::shared_ptr<ModelAPI_Folder> Model_Objects::createFolder(
1344     const std::shared_ptr<ModelAPI_Feature>& theBeforeThis)
1345 {
1346   FolderPtr aFolder(new ModelAPI_Folder);
1347   if (!aFolder)
1348     return aFolder;
1349
1350   TDF_Label aFeaturesLab = featuresLabel();
1351   TDF_Label aFolderLab = aFeaturesLab.NewChild();
1352   // store feature in the features array: before "initData" because in macro features
1353   // in initData it creates new features, appeared later than this
1354   TDF_Label aPrevFeatureLab;
1355   if (theBeforeThis.get()) { // searching for the previous feature label
1356     std::shared_ptr<Model_Data> aPrevData =
1357         std::dynamic_pointer_cast<Model_Data>(theBeforeThis->data());
1358     if (aPrevData.get()) {
1359       int anIndex = kUNDEFINED_FEATURE_INDEX;
1360       aPrevFeatureLab = nextLabel(aPrevData->label().Father(), anIndex, true);
1361     }
1362   } else { // find the label of the last feature
1363     Handle(TDataStd_ReferenceArray) aRefs;
1364     if (aFeaturesLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
1365       aPrevFeatureLab = aRefs->Value(aRefs->Upper());
1366   }
1367   AddToRefArray(aFeaturesLab, aFolderLab, aPrevFeatureLab);
1368
1369   // keep the feature ID to restore document later correctly
1370   TDataStd_Comment::Set(aFolderLab, ModelAPI_Folder::ID().c_str());
1371   myFolders.Bind(aFolderLab, aFolder);
1372   // must be before the event sending: for OB the feature is already added
1373   updateHistory(ModelAPI_Folder::group());
1374   updateHistory(ModelAPI_Feature::group());
1375
1376   // must be after binding to the map because of "Box" macro feature that
1377   // creates other features in "initData"
1378   initData(aFolder, aFolderLab, TAG_FEATURE_ARGUMENTS);
1379   // event: folder is added, must be before "initData" to update OB correctly on Duplicate:
1380   // first new part, then the content
1381   static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
1382   ModelAPI_EventCreator::get()->sendUpdated(aFolder, anEvent);
1383
1384   return aFolder;
1385 }
1386
1387 void Model_Objects::removeFolder(std::shared_ptr<ModelAPI_Folder> theFolder)
1388 {
1389   std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theFolder->data());
1390   if (!aData.get() || !aData->isValid())
1391     return;
1392
1393   // this must be before erase since theFolder erasing removes all information about it
1394   clearHistory(theFolder);
1395   // erase fields
1396   theFolder->erase();
1397
1398   TDF_Label aFolderLabel = aData->label().Father();
1399   if (myFolders.IsBound(aFolderLabel))
1400     myFolders.UnBind(aFolderLabel);
1401
1402   static Events_ID EVENT_DISP = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
1403   ModelAPI_EventCreator::get()->sendUpdated(theFolder, EVENT_DISP);
1404   // erase all attributes under the label of feature
1405   aFolderLabel.ForgetAllAttributes();
1406   // remove it from the references array
1407   RemoveFromRefArray(featuresLabel(), aFolderLabel);
1408   // event: feature is deleted
1409   ModelAPI_EventCreator::get()->sendDeleted(theFolder->document(), ModelAPI_Folder::group());
1410   updateHistory(ModelAPI_Folder::group());
1411   updateHistory(ModelAPI_Feature::group());
1412 }
1413
1414 // Returns one of the limiting features of the list
1415 static FeaturePtr limitingFeature(std::list<FeaturePtr>& theFeatures, const bool isLast)
1416 {
1417   FeaturePtr aFeature;
1418   if (isLast) {
1419     aFeature = theFeatures.back();
1420     theFeatures.pop_back();
1421   } else {
1422     aFeature = theFeatures.front();
1423     theFeatures.pop_front();
1424   }
1425   return aFeature;
1426 }
1427
1428 // Verify the feature is sub-element in composite feature or it is not used in the history
1429 static bool isSkippedFeature(FeaturePtr theFeature)
1430 {
1431   bool isSub = ModelAPI_Tools::compositeOwner(theFeature).get() != NULL;
1432   return isSub || (theFeature && !theFeature->isInHistory());
1433 }
1434
1435 std::shared_ptr<ModelAPI_Folder> Model_Objects::findFolder(
1436       const std::list<std::shared_ptr<ModelAPI_Feature> >& theFeatures,
1437       const bool theBelow)
1438 {
1439   if (theFeatures.empty())
1440     return FolderPtr(); // nothing to move
1441
1442   TDF_Label aFeaturesLab = featuresLabel();
1443   Handle(TDataStd_ReferenceArray) aRefs;
1444   if (!aFeaturesLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
1445     return FolderPtr(); // no reference array (something is wrong)
1446
1447   std::list<std::shared_ptr<ModelAPI_Feature> > aFeatures = theFeatures;
1448   std::shared_ptr<ModelAPI_Feature> aLimitingFeature = limitingFeature(aFeatures, theBelow);
1449
1450   std::shared_ptr<Model_Data> aData =
1451       std::static_pointer_cast<Model_Data>(aLimitingFeature->data());
1452   if (!aData || !aData->isValid())
1453     return FolderPtr(); // invalid feature
1454
1455   // label of the first feature in the list for fast searching
1456   TDF_Label aFirstFeatureLabel = aData->label().Father();
1457
1458   // find a folder above the features and
1459   // check the given features represent a sequential list of objects following the folder
1460   FolderPtr aFoundFolder;
1461   TDF_Label aLastFeatureInFolder;
1462   int aRefIndex = aRefs->Lower();
1463   for(; aRefIndex <= aRefs->Upper(); ++aRefIndex) { // iterate all existing features
1464     TDF_Label aCurLabel = aRefs->Value(aRefIndex);
1465     if (IsEqual(aCurLabel, aFirstFeatureLabel))
1466       break; // no need to continue searching
1467
1468     // searching the folder below, just continue to search last feature from the list
1469     if (theBelow)
1470       continue;
1471
1472     // if feature is in sub-component, skip it
1473     FeaturePtr aCurFeature = feature(aCurLabel);
1474     if (isSkippedFeature(aCurFeature))
1475       continue;
1476
1477     if (!aLastFeatureInFolder.IsNull()) {
1478       if (IsEqual(aCurLabel, aLastFeatureInFolder))
1479         aLastFeatureInFolder.Nullify(); // the last feature in the folder is achieved
1480       continue;
1481     }
1482
1483     const ObjectPtr& aFolderObj = folder(aCurLabel);
1484     if (aFolderObj.get()) {
1485       aFoundFolder = std::dynamic_pointer_cast<ModelAPI_Folder>(aFolderObj);
1486       AttributeReferencePtr aLastFeatAttr =
1487           aFoundFolder->reference(ModelAPI_Folder::LAST_FEATURE_ID());
1488       if (aLastFeatAttr) {
1489         // setup iterating inside a folder to find last feature
1490         ObjectPtr aLastFeature = aLastFeatAttr->value();
1491         if (aLastFeature) {
1492           aData = std::static_pointer_cast<Model_Data>(aLastFeature->data());
1493           if (aData && aData->isValid())
1494             aLastFeatureInFolder = aData->label().Father();
1495         }
1496       }
1497     }
1498   }
1499
1500   if (theBelow && aRefIndex < aRefs->Upper()) {
1501     TDF_Label aLabel;
1502     // skip following features which are sub-components or not in history
1503     for (int anIndex = aRefIndex + 1; anIndex <= aRefs->Upper(); ++anIndex) {
1504       aLabel = aRefs->Value(anIndex);
1505       FeaturePtr aCurFeature = feature(aLabel);
1506       if (!isSkippedFeature(aCurFeature))
1507         break;
1508     }
1509     // check the next object is a folder
1510     aFoundFolder = std::dynamic_pointer_cast<ModelAPI_Folder>(folder(aLabel));
1511   }
1512
1513   if (!aLastFeatureInFolder.IsNull() || // the last feature of the folder above is not found
1514       !aFoundFolder)
1515     return FolderPtr();
1516
1517   // check the given features are sequential list
1518   int aStep = theBelow ? -1 : 1;
1519   for (aRefIndex += aStep;
1520        !aFeatures.empty() && aRefIndex >= aRefs->Lower() && aRefIndex <= aRefs->Upper();
1521        aRefIndex += aStep) {
1522     TDF_Label aCurLabel = aRefs->Value(aRefIndex);
1523     // if feature is in sub-component, skip it
1524     FeaturePtr aCurFeature = feature(aCurLabel);
1525     if (isSkippedFeature(aCurFeature))
1526       continue;
1527
1528     aLimitingFeature = limitingFeature(aFeatures, theBelow);
1529     if (!aCurFeature->data()->isEqual(aLimitingFeature->data()))
1530       return FolderPtr(); // not a sequential list
1531   }
1532
1533   return aFoundFolder;
1534 }
1535
1536 bool Model_Objects::moveToFolder(
1537       const std::list<std::shared_ptr<ModelAPI_Feature> >& theFeatures,
1538       const std::shared_ptr<ModelAPI_Folder>& theFolder)
1539 {
1540   if (theFeatures.empty() || !theFolder)
1541     return false;
1542
1543   // labels for the folder and last feature in the list
1544   TDF_Label aFolderLabel, aLastFeatureLabel;
1545   std::shared_ptr<Model_Data> aData =
1546       std::static_pointer_cast<Model_Data>(theFolder->data());
1547   if (aData && aData->isValid())
1548     aFolderLabel = aData->label().Father();
1549   aData = std::static_pointer_cast<Model_Data>(theFeatures.back()->data());
1550   if (aData && aData->isValid())
1551     aLastFeatureLabel = aData->label().Father();
1552
1553   if (aFolderLabel.IsNull() || aLastFeatureLabel.IsNull())
1554     return false;
1555
1556   AttributeReferencePtr aFirstFeatAttr =
1557       theFolder->reference(ModelAPI_Folder::FIRST_FEATURE_ID());
1558   AttributeReferencePtr aLastFeatAttr =
1559       theFolder->reference(ModelAPI_Folder::LAST_FEATURE_ID());
1560   bool initFirstAttr = !aFirstFeatAttr->value().get();
1561   bool initLastAttr  = !aLastFeatAttr->value().get();
1562
1563   // check the folder is below the list of features
1564   bool isFolderBelow = false;
1565   TDF_Label aFeaturesLab = featuresLabel();
1566   Handle(TDataStd_ReferenceArray) aRefs;
1567   if (!aFeaturesLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
1568     return false; // no reference array (something is wrong)
1569   for (int aRefIndex = aRefs->Lower(); aRefIndex <= aRefs->Upper(); ++aRefIndex) {
1570     TDF_Label aCurLabel = aRefs->Value(aRefIndex);
1571     if (aCurLabel == aFolderLabel)
1572       break; // folder is above the features
1573     else if (aCurLabel == aLastFeatureLabel) {
1574       isFolderBelow = true;
1575       break;
1576     }
1577   }
1578
1579   if (isFolderBelow) {
1580     aData = std::static_pointer_cast<Model_Data>(theFeatures.front()->data());
1581     if (!aData || !aData->isValid())
1582       return false;
1583     TDF_Label aPrevFeatureLabel = aData->label().Father();
1584     // label of the feature before the first feature in the list
1585     for (int aRefIndex = aRefs->Lower(); aRefIndex <= aRefs->Upper(); ++aRefIndex)
1586       if (aPrevFeatureLabel == aRefs->Value(aRefIndex)) {
1587         if (aRefIndex == aRefs->Lower())
1588           aPrevFeatureLabel.Nullify();
1589         else
1590           aPrevFeatureLabel = aRefs->Value(aRefIndex - 1);
1591         break;
1592       }
1593
1594     // move the folder in the list of references before the first feature
1595     RemoveFromRefArray(aFeaturesLab, aFolderLabel);
1596     AddToRefArray(aFeaturesLab, aFolderLabel, aPrevFeatureLabel);
1597     // update first feature of the folder
1598     initFirstAttr = true;
1599   } else {
1600     // update last feature of the folder
1601     initLastAttr = true;
1602   }
1603
1604   if (initFirstAttr)
1605     aFirstFeatAttr->setValue(theFeatures.front());
1606   if (initLastAttr)
1607     aLastFeatAttr->setValue(theFeatures.back());
1608
1609   updateHistory(ModelAPI_Feature::group());
1610   return true;
1611 }
1612
1613 static FolderPtr isExtractionCorrect(const FolderPtr& theFirstFeatureFolder,
1614                                      const FolderPtr& theLastFeatureFolder,
1615                                      bool& isExtractBefore)
1616 {
1617   if (theFirstFeatureFolder.get()) {
1618     if (theLastFeatureFolder.get())
1619       return theFirstFeatureFolder == theLastFeatureFolder ? theFirstFeatureFolder : FolderPtr();
1620     else
1621       isExtractBefore = true;
1622     return theFirstFeatureFolder;
1623   } else if (theLastFeatureFolder.get()) {
1624     isExtractBefore = false;
1625     return theLastFeatureFolder;
1626   }
1627   // no folder found
1628   return FolderPtr();
1629 }
1630
1631 bool Model_Objects::removeFromFolder(
1632       const std::list<std::shared_ptr<ModelAPI_Feature> >& theFeatures,
1633       const bool theBefore)
1634 {
1635   if (theFeatures.empty())
1636     return false;
1637
1638   FolderPtr aFirstFeatureFolder =
1639       inFolder(theFeatures.front(), ModelAPI_Folder::FIRST_FEATURE_ID());
1640   FolderPtr aLastFeatureFolder =
1641       inFolder(theFeatures.back(),  ModelAPI_Folder::LAST_FEATURE_ID());
1642
1643   bool isExtractBeforeFolder = theBefore;
1644   FolderPtr aFoundFolder =
1645       isExtractionCorrect(aFirstFeatureFolder, aLastFeatureFolder, isExtractBeforeFolder);
1646   if (!aFoundFolder)
1647     return false; // list of features cannot be extracted
1648
1649   // references of the current folder
1650   ObjectPtr aFolderStartFeature;
1651   ObjectPtr aFolderEndFeature;
1652   if (aFirstFeatureFolder != aLastFeatureFolder) {
1653     aFolderStartFeature = aFoundFolder->reference(ModelAPI_Folder::FIRST_FEATURE_ID())->value();
1654     aFolderEndFeature   = aFoundFolder->reference(ModelAPI_Folder::LAST_FEATURE_ID())->value();
1655   }
1656
1657   FeaturePtr aFeatureToFind = isExtractBeforeFolder ? theFeatures.back() : theFeatures.front();
1658   std::shared_ptr<Model_Data> aData =
1659       std::static_pointer_cast<Model_Data>(aFeatureToFind->data());
1660   if (!aData || !aData->isValid())
1661     return false;
1662   TDF_Label aLabelToFind = aData->label().Father();
1663
1664   // search the label in the list of references
1665   TDF_Label aFeaturesLab = featuresLabel();
1666   Handle(TDataStd_ReferenceArray) aRefs;
1667   if (!aFeaturesLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
1668     return false; // no reference array (something is wrong)
1669   int aRefIndex = aRefs->Lower();
1670   for (; aRefIndex <= aRefs->Upper(); ++aRefIndex)
1671     if (aRefs->Value(aRefIndex) == aLabelToFind)
1672       break;
1673
1674   // update folder position
1675   if (isExtractBeforeFolder) {
1676     aData = std::dynamic_pointer_cast<Model_Data>(aFoundFolder->data());
1677     TDF_Label aFolderLabel = aData->label().Father();
1678     TDF_Label aPrevFeatureLabel = aRefs->Value(aRefIndex);
1679     // update start reference of the folder
1680     if (aFolderStartFeature.get()) {
1681       FeaturePtr aNewStartFeature;
1682       do { // skip all features placed in the composite features
1683         aPrevFeatureLabel = aRefs->Value(aRefIndex++);
1684         aNewStartFeature =
1685             aRefIndex <= aRefs->Upper() ? feature(aRefs->Value(aRefIndex)) : FeaturePtr();
1686       } while (aNewStartFeature && isSkippedFeature(aNewStartFeature));
1687       aFolderStartFeature = aNewStartFeature;
1688     }
1689     // move the folder in the list of references after the last feature from the list
1690     RemoveFromRefArray(aFeaturesLab, aFolderLabel);
1691     AddToRefArray(aFeaturesLab, aFolderLabel, aPrevFeatureLabel);
1692   } else {
1693     // update end reference of the folder
1694     if (aFolderEndFeature.get()) {
1695       FeaturePtr aNewEndFeature;
1696       do { // skip all features placed in the composite features
1697         --aRefIndex;
1698         aNewEndFeature =
1699             aRefIndex >= aRefs->Lower() ? feature(aRefs->Value(aRefIndex)) : FeaturePtr();
1700       } while (aNewEndFeature && isSkippedFeature(aNewEndFeature));
1701       aFolderEndFeature = aNewEndFeature;
1702     }
1703   }
1704
1705   // update folder references
1706   aFoundFolder->reference(ModelAPI_Folder::FIRST_FEATURE_ID())->setValue(aFolderStartFeature);
1707   aFoundFolder->reference(ModelAPI_Folder::LAST_FEATURE_ID())->setValue(aFolderEndFeature);
1708
1709   updateHistory(ModelAPI_Feature::group());
1710   return true;
1711 }
1712
1713 FolderPtr Model_Objects::findContainingFolder(const FeaturePtr& theFeature, int& theIndexInFolder)
1714 {
1715   // search the label in the list of references
1716   TDF_Label aFeaturesLab = featuresLabel();
1717   Handle(TDataStd_ReferenceArray) aRefs;
1718   if (!aFeaturesLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
1719     return FolderPtr(); // no reference array (something is wrong)
1720
1721   std::shared_ptr<Model_Data> aData =
1722       std::static_pointer_cast<Model_Data>(theFeature->data());
1723   if (!aData || !aData->isValid())
1724     return FolderPtr();
1725   TDF_Label aLabelToFind = aData->label().Father();
1726
1727   theIndexInFolder = -1;
1728   FolderPtr aFoundFolder;
1729   TDF_Label aLastFeatureLabel;
1730
1731   for (int aRefIndex = aRefs->Lower(); aRefIndex <= aRefs->Upper(); ++aRefIndex) {
1732     TDF_Label aCurLabel = aRefs->Value(aRefIndex);
1733
1734     if (aFoundFolder)
1735       ++theIndexInFolder;
1736
1737     if (aCurLabel == aLabelToFind) { // the feature is reached
1738       if (aFoundFolder) {
1739         if (isSkippedFeature(theFeature)) {
1740           theIndexInFolder = -1;
1741           return FolderPtr();
1742         }
1743         // decrease the index of the feature in the folder by the number of skipped features
1744         for (int anIndex = theIndexInFolder - 1; anIndex > 0; anIndex--) {
1745           aCurLabel = aRefs->Value(aRefIndex - anIndex);
1746           if (isSkippedFeature(feature(aCurLabel)))
1747             theIndexInFolder--;
1748         }
1749       }
1750       return aFoundFolder;
1751     }
1752
1753     if (!aFoundFolder) {
1754       // if the current label refers to a folder, feel all necessary data
1755       const ObjectPtr& aFolderObj = folder(aCurLabel);
1756       if (aFolderObj.get()) {
1757         aFoundFolder = std::dynamic_pointer_cast<ModelAPI_Folder>(aFolderObj);
1758         theIndexInFolder = -1;
1759
1760         AttributeReferencePtr aLastRef =
1761             aFoundFolder->reference(ModelAPI_Folder::LAST_FEATURE_ID());
1762         if (aLastRef->value()) {
1763           aData = std::static_pointer_cast<Model_Data>(aLastRef->value()->data());
1764           if (aData && aData->isValid())
1765             aLastFeatureLabel = aData->label().Father();
1766         } else // folder is empty
1767           aFoundFolder = FolderPtr();
1768       }
1769     } else if (aLastFeatureLabel == aCurLabel) {
1770       // folder is finished, clear all stored data
1771       theIndexInFolder = -1;
1772       aFoundFolder = FolderPtr();
1773     }
1774   }
1775
1776   // folder is not found
1777   theIndexInFolder = -1;
1778   return FolderPtr();
1779 }
1780
1781
1782 std::shared_ptr<ModelAPI_Feature> Model_Objects::feature(
1783     const std::shared_ptr<ModelAPI_Result>& theResult)
1784 {
1785   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(theResult->data());
1786   if (aData.get() && aData->isValid()) {
1787     TDF_Label aFeatureLab = aData->label().Father().Father().Father();
1788     FeaturePtr aFeature = feature(aFeatureLab);
1789     while(!aFeature.get() && aFeatureLab.Depth() > 1) { // this may be sub-result of result
1790       aFeatureLab = aFeatureLab.Father().Father();
1791       aFeature = feature(aFeatureLab);
1792     }
1793     return aFeature;
1794   }
1795   return FeaturePtr();
1796 }
1797
1798 std::string Model_Objects::featureResultGroup(FeaturePtr theFeature)
1799 {
1800   if (theFeature->data()->isValid()) {
1801     TDF_ChildIterator aLabIter(resultLabel(theFeature->data(), 0).Father());
1802     if (aLabIter.More()) {
1803       TDF_Label anArgLab = aLabIter.Value();
1804       Handle(TDataStd_Comment) aGroup;
1805       if (aLabIter.Value().FindAttribute(TDataStd_Comment::GetID(), aGroup)) {
1806         return TCollection_AsciiString(aGroup->Get()).ToCString();
1807       }
1808     }
1809   }
1810   static std::string anEmpty;
1811   return anEmpty; // not found
1812 }
1813
1814 void Model_Objects::updateResults(FeaturePtr theFeature, std::set<FeaturePtr>& theProcessed)
1815 {
1816   if (theProcessed.find(theFeature) != theProcessed.end())
1817     return;
1818   theProcessed.insert(theFeature);
1819   // for composites update subs recursively (sketch elements results are needed for the sketch)
1820   CompositeFeaturePtr aComp = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theFeature);
1821   if (aComp.get() && aComp->getKind() != "Part") { // don't go inside of parts sub-features
1822     // update subs of composites first
1823     int aSubNum = aComp->numberOfSubs();
1824     for(int a = 0; a < aSubNum; a++) {
1825       FeaturePtr aSub = aComp->subFeature(a);
1826       updateResults(aComp->subFeature(a), theProcessed);
1827     }
1828   }
1829
1830   // check the existing results and remove them if there is nothing on the label
1831   std::list<ResultPtr>::const_iterator aResIter = theFeature->results().cbegin();
1832   while(aResIter != theFeature->results().cend()) {
1833     ResultPtr aBody = std::dynamic_pointer_cast<ModelAPI_Result>(*aResIter);
1834     if (aBody.get()) {
1835       std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(aBody->data());
1836       if (!aData.get() || !aData->isValid() || (!aBody->isDisabled() && aData->isDeleted())) {
1837         // found a disappeared result => remove it
1838         theFeature->eraseResultFromList(aBody);
1839         // start iterate from beginning because iterator is corrupted by removing
1840         aResIter = theFeature->results().cbegin();
1841         continue;
1842       }
1843     }
1844     aResIter++;
1845   }
1846   // it may be on undo
1847   if (!theFeature->data() || !theFeature->data()->isValid() || theFeature->isDisabled())
1848     return;
1849   // check that results are presented on all labels
1850   int aResSize = int(theFeature->results().size());
1851   TDF_ChildIterator aLabIter(resultLabel(theFeature->data(), 0).Father());
1852   for(; aLabIter.More(); aLabIter.Next()) {
1853     // here must be GUID of the feature
1854     int aResIndex = aLabIter.Value().Tag() - 1;
1855     ResultPtr aNewBody;
1856     if (aResSize <= aResIndex) {
1857       TDF_Label anArgLab = aLabIter.Value();
1858       Handle(TDataStd_Comment) aGroup;
1859       if (anArgLab.FindAttribute(TDataStd_Comment::GetID(), aGroup)) {
1860         if (aGroup->Get() == ModelAPI_ResultBody::group().c_str()) {
1861           aNewBody = createBody(theFeature->data(), aResIndex);
1862         } else if (aGroup->Get() == ModelAPI_ResultPart::group().c_str()) {
1863           if (aResIndex <= theFeature->results().size()) { // to avoid crash if previous execute
1864             // for index = 0 erases result
1865             std::shared_ptr<ModelAPI_ResultPart> aNewP = createPart(theFeature->data(), aResIndex);
1866             theFeature->setResult(aNewP, aResIndex);
1867             if (!aNewP->partDoc().get())
1868               // create the part result: it is better to restore the previous result if possible
1869               theFeature->execute();
1870           }
1871         } else if (aGroup->Get() == ModelAPI_ResultConstruction::group().c_str()) {
1872           ResultConstructionPtr aConstr = createConstruction(theFeature->data(), aResIndex);
1873           if (!aConstr->updateShape())
1874             theFeature->execute(); // not stored shape in the data structure, execute to have it
1875           else
1876             theFeature->setResult(aConstr, aResIndex); // result is ready without execution
1877         } else if (aGroup->Get() == ModelAPI_ResultGroup::group().c_str()) {
1878           aNewBody = createGroup(theFeature->data(), aResIndex);
1879         } else if (aGroup->Get() == ModelAPI_ResultField::group().c_str()) {
1880           ResultFieldPtr aField = createField(theFeature->data(), aResIndex);
1881           aField->updateSteps(); // to refresh the internal data
1882           aNewBody = aField;
1883         } else if (aGroup->Get() == ModelAPI_ResultParameter::group().c_str()) {
1884           theFeature->attributeChanged("expression"); // just produce a value
1885         } else {
1886           Events_InfoMessage("Model_Objects", "Unknown type of result is found in the document:")
1887             .arg(TCollection_AsciiString(aGroup->Get()).ToCString()).send();
1888         }
1889       }
1890       if (aNewBody && !aNewBody->data()->isDeleted()) {
1891         theFeature->setResult(aNewBody, aResIndex);
1892       }
1893     }
1894   }
1895   if (aResSize > 0) { // check there exist a body that must be updated
1896     std::list<ResultPtr>::const_iterator aRes = theFeature->results().cbegin();
1897     for (; aResSize && aRes != theFeature->results().cend(); aRes++, aResSize++) {
1898       if ((*aRes)->data()->isValid()) {
1899         if ((*aRes)->groupName() == ModelAPI_ResultBody::group()) {
1900           ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(*aRes);
1901           aBody->updateSubs(aBody->shape(), false);
1902         } else if ((*aRes)->groupName() == ModelAPI_ResultConstruction::group()) {
1903           // update the cashed myShape presented in construction
1904           ResultConstructionPtr aConstr =
1905             std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
1906           aConstr->updateShape();
1907         }
1908       }
1909     }
1910   }
1911 }
1912
1913 ResultPtr Model_Objects::findByName(const std::string theName)
1914 {
1915   ResultPtr aResult;
1916   FeaturePtr aResFeature; // keep feature to return the latest one
1917   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator anObjIter(myFeatures);
1918   for(; anObjIter.More(); anObjIter.Next()) {
1919     FeaturePtr& aFeature = anObjIter.ChangeValue();
1920     if (!aFeature.get() || aFeature->isDisabled()) // may be on close
1921       continue;
1922     std::list<ResultPtr> allResults;
1923     ModelAPI_Tools::allResults(aFeature, allResults);
1924     std::list<ResultPtr>::iterator aRIter = allResults.begin();
1925     for (; aRIter != allResults.cend(); aRIter++) {
1926       ResultPtr aRes = *aRIter;
1927       if (aRes.get() && aRes->data() && aRes->data()->isValid() && !aRes->isDisabled() &&
1928           aRes->data()->name() == theName)
1929       {
1930         if (!aResult.get() || isLater(aFeature, aResFeature)) { // select the latest
1931           aResult = aRes;
1932           aResFeature = aFeature;
1933         }
1934       }
1935     }
1936   }
1937   return aResult;
1938 }
1939
1940 TDF_Label Model_Objects::nextLabel(TDF_Label theCurrent, int& theIndex, const bool theReverse)
1941 {
1942   Handle(TDataStd_ReferenceArray) aRefs;
1943   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
1944     int aStart = theIndex == kUNDEFINED_FEATURE_INDEX ? aRefs->Lower() : theIndex;
1945     for(int a = aStart; a <= aRefs->Upper(); a++) { // iterate all existing features
1946       TDF_Label aCurLab = aRefs->Value(a);
1947       if (aCurLab.IsEqual(theCurrent)) {
1948         a += theReverse ? -1 : 1;
1949         if (a >= aRefs->Lower() && a <= aRefs->Upper()) {
1950           theIndex = a;
1951           return aRefs->Value(a);
1952         }
1953         break; // finish iteration: it's last feature
1954       }
1955     }
1956   }
1957   return TDF_Label();
1958 }
1959
1960 FeaturePtr Model_Objects::nextFeature(FeaturePtr theCurrent, int& theIndex, const bool theReverse)
1961 {
1962   std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theCurrent->data());
1963   if (aData.get() && aData->isValid()) {
1964     TDF_Label aFeatureLabel = aData->label().Father();
1965     do {
1966       TDF_Label aNextLabel = nextLabel(aFeatureLabel, theIndex, theReverse);
1967       if (aNextLabel.IsNull())
1968         break; // the last or something is wrong
1969       FeaturePtr aFound = feature(aNextLabel);
1970       if (aFound)
1971         return aFound; // the feature is found
1972       // if the next label is a folder, skip it
1973       aFeatureLabel = folder(aNextLabel).get() ? aNextLabel : TDF_Label();
1974     } while (!aFeatureLabel.IsNull());
1975   }
1976   return FeaturePtr(); // not found, last, or something is wrong
1977 }
1978
1979 FeaturePtr Model_Objects::firstFeature()
1980 {
1981   Handle(TDataStd_ReferenceArray) aRefs;
1982   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
1983     return feature(aRefs->Value(aRefs->Lower()));
1984   }
1985   return FeaturePtr(); // no features at all
1986 }
1987
1988 FeaturePtr Model_Objects::lastFeature()
1989 {
1990   Handle(TDataStd_ReferenceArray) aRefs;
1991   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
1992     // comment this because of #2674 - features are removed from array on deactivation of Part
1993     /*FeaturePtr aLast = feature(aRefs->Value(aRefs->Upper()));
1994     if (!aLast.get() && aRefs->Length() != 0) { // erase the invalid feature from the array
1995       RemoveFromRefArray(featuresLabel(), aRefs->Value(aRefs->Upper()));
1996       return lastFeature(); // try once again, after the last was removed
1997     }*/
1998     return feature(aRefs->Value(aRefs->Upper()));
1999   }
2000   return FeaturePtr(); // no features at all
2001 }
2002
2003 bool Model_Objects::isLater(FeaturePtr theLater, FeaturePtr theCurrent) const
2004 {
2005   std::shared_ptr<Model_Data> aLaterD = std::static_pointer_cast<Model_Data>(theLater->data());
2006   std::shared_ptr<Model_Data> aCurrentD = std::static_pointer_cast<Model_Data>(theCurrent->data());
2007   if (aLaterD.get() && aLaterD->isValid() && aCurrentD.get() && aCurrentD->isValid()) {
2008     TDF_Label aLaterL = aLaterD->label().Father();
2009     TDF_Label aCurrentL = aCurrentD->label().Father();
2010     int aLaterI = -1, aCurentI = -1; // not found yet state
2011     Handle(TDataStd_ReferenceArray) aRefs;
2012     if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
2013       for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) { // iterate all existing features
2014         TDF_Label aCurLab = aRefs->Value(a);
2015         if (aCurLab.IsEqual(aLaterL)) {
2016           aLaterI = a;
2017         } else if (aCurLab.IsEqual(aCurrentL)) {
2018           aCurentI = a;
2019         } else continue;
2020         if (aLaterI != -1 && aCurentI != -1) // both are found
2021           return aLaterI > aCurentI;
2022       }
2023     }
2024   }
2025   return false; // not found, or something is wrong
2026 }
2027
2028 std::list<std::shared_ptr<ModelAPI_Object> > Model_Objects::allObjects()
2029 {
2030   std::list<std::shared_ptr<ModelAPI_Object> > aResult;
2031   Handle(TDataStd_ReferenceArray) aRefs;
2032   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
2033     for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
2034       ObjectPtr anObject = object(aRefs->Value(a));
2035       if (!anObject.get()) // is it a folder?
2036         anObject = folder(aRefs->Value(a));
2037       if (anObject.get())
2038         aResult.push_back(anObject);
2039     }
2040   }
2041   return aResult;
2042 }
2043
2044 std::list<std::shared_ptr<ModelAPI_Feature> > Model_Objects::allFeatures()
2045 {
2046   std::list<std::shared_ptr<ModelAPI_Feature> > aResult;
2047   Handle(TDataStd_ReferenceArray) aRefs;
2048   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
2049     for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
2050       FeaturePtr aFeature = feature(aRefs->Value(a));
2051       if (aFeature.get())
2052         aResult.push_back(aFeature);
2053     }
2054   }
2055   return aResult;
2056 }
2057
2058 int Model_Objects::numInternalFeatures()
2059 {
2060   Handle(TDataStd_ReferenceArray) aRefs;
2061   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
2062     return aRefs->Upper() - aRefs->Lower() + 1;
2063   }
2064   return 0; // invalid
2065 }
2066
2067 std::shared_ptr<ModelAPI_Feature> Model_Objects::internalFeature(const int theIndex)
2068 {
2069   Handle(TDataStd_ReferenceArray) aRefs;
2070   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
2071     return feature(aRefs->Value(aRefs->Lower() + theIndex));
2072   }
2073   return FeaturePtr(); // invalid
2074 }
2075
2076 Standard_Integer HashCode(const TDF_Label& theLab, const Standard_Integer theUpper)
2077 {
2078   return TDF_LabelMapHasher::HashCode(theLab, theUpper);
2079
2080 }
2081 Standard_Boolean IsEqual(const TDF_Label& theLab1, const TDF_Label& theLab2)
2082 {
2083   return TDF_LabelMapHasher::IsEqual(theLab1, theLab2);
2084 }