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