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