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