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