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