]> SALOME platform Git repositories - modules/shaper.git/blob - src/Model/Model_Objects.cpp
Salome HOME
Debug of "Concealment" behavior in multiple hierarchy case.
[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             if (aSubData->label().Father().IsEqual(aSubLab.ChangeValue())) {
580               aCurrentResult = aSub;
581               break;
582             }
583           }
584         }
585         if (a == aNumSubs) // not found an appropriate sub-result of result
586           return ObjectPtr();
587       } else { // iterate results of feature
588         const std::list<ResultPtr>& aResults = aFeature->results();
589         std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.cbegin();
590         for(; aRIter != aResults.cend(); aRIter++) {
591           std::shared_ptr<Model_Data> aResData = std::dynamic_pointer_cast<Model_Data>((*aRIter)->data());
592           if (aResData->label().Father().IsEqual(aSubLab.ChangeValue())) {
593             aCurrentResult = *aRIter;
594             break;
595           }
596         }
597         if (aRIter == aResults.cend()) // not found an appropriate result of feature
598           return ObjectPtr();
599       }
600     }
601     return aCurrentResult;
602   }
603   return ObjectPtr();  // not found
604 }
605
606 ObjectPtr Model_Objects::object(const std::string& theGroupID,
607                                 const int theIndex,
608                                 const bool theAllowFolder)
609 {
610   if (theIndex == -1)
611     return ObjectPtr();
612   createHistory(theGroupID);
613   const std::string& aGroupID = groupNameFoldering(theGroupID, theAllowFolder);
614   const std::vector<ObjectPtr>& aVec = myHistory[theGroupID];
615   //if (aVec.size() <= theIndex)
616   //  return aVec[aVec.size() - 1]; // too high index requested (to avoid crash in #2360)
617   return aGroupID.empty() ? myHistory[theGroupID][theIndex] : myHistory[aGroupID][theIndex];
618 }
619
620 std::shared_ptr<ModelAPI_Object> Model_Objects::objectByName(
621     const std::string& theGroupID, const std::string& theName)
622 {
623   createHistory(theGroupID);
624   if (theGroupID == ModelAPI_Feature::group()) { // searching among features (in history or not)
625     std::list<std::shared_ptr<ModelAPI_Feature> > allObjs = allFeatures();
626     std::list<std::shared_ptr<ModelAPI_Feature> >::iterator anObjIter = allObjs.begin();
627     for(; anObjIter != allObjs.end(); anObjIter++) {
628       if ((*anObjIter)->data()->name() == theName)
629         return *anObjIter;
630     }
631   } else { // searching among results (concealed or not)
632     std::list<std::shared_ptr<ModelAPI_Feature> > allObjs = allFeatures();
633     std::list<std::shared_ptr<ModelAPI_Feature> >::iterator anObjIter = allObjs.begin();
634     for(; anObjIter != allObjs.end(); anObjIter++) {
635       std::list<ResultPtr> allRes;
636       ModelAPI_Tools::allResults(*anObjIter, allRes);
637       for(std::list<ResultPtr>::iterator aRes = allRes.begin(); aRes != allRes.end(); aRes++) {
638         if (aRes->get() && (*aRes)->groupName() == theGroupID) {
639           if ((*aRes)->data()->name() == theName)
640             return *aRes;
641         }
642       }
643     }
644   }
645   // not found
646   return ObjectPtr();
647 }
648
649 const int Model_Objects::index(std::shared_ptr<ModelAPI_Object> theObject,
650                                const bool theAllowFolder)
651 {
652   std::string aGroup = theObject->groupName();
653   // treat folder as feature
654   if (aGroup == ModelAPI_Folder::group())
655     aGroup = ModelAPI_Feature::group();
656   createHistory(aGroup);
657
658   // get the group of features out of folder (if enabled)
659   if (theAllowFolder && !groupNameFoldering(aGroup, theAllowFolder).empty())
660     aGroup = groupNameFoldering(aGroup, theAllowFolder);
661
662   std::vector<ObjectPtr>& allObjs = myHistory[aGroup];
663   std::vector<ObjectPtr>::iterator anObjIter = allObjs.begin(); // iterate to search object
664   for(int anIndex = 0; anObjIter != allObjs.end(); anObjIter++, anIndex++) {
665     if ((*anObjIter) == theObject)
666       return anIndex;
667   }
668   // not found
669   return -1;
670 }
671
672 int Model_Objects::size(const std::string& theGroupID, const bool theAllowFolder)
673 {
674   createHistory(theGroupID);
675   const std::string& aGroupID = groupNameFoldering(theGroupID, theAllowFolder);
676   return aGroupID.empty() ? int(myHistory[theGroupID].size()) : int(myHistory[aGroupID].size());
677 }
678
679 std::shared_ptr<ModelAPI_Object> Model_Objects::parent(
680   const std::shared_ptr<ModelAPI_Object> theChild)
681 {
682   if (theChild.get()) {
683     std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(theChild->data());
684     TDF_Label aLab = aData->label();
685     if (!aLab.IsNull() && aLab.Depth() > 2) {
686       ObjectPtr anObj = object(aLab.Father().Father().Father());
687       return anObj;
688     }
689   }
690   return ObjectPtr();
691 }
692
693
694 void Model_Objects::allResults(const std::string& theGroupID, std::list<ResultPtr>& theResults)
695 {
696   // iterate the array of references and get feature by feature from the array
697   Handle(TDataStd_ReferenceArray) aRefs;
698   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
699     for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
700       FeaturePtr aFeature = feature(aRefs->Value(a));
701       if (aFeature.get()) {
702         const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
703         std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
704         for (; aRIter != aResults.cend(); aRIter++) {
705           ResultPtr aRes = *aRIter;
706           if (aRes->groupName() != theGroupID) break; // feature have only same group results
707           // iterate also concealed: ALL RESULTS (for translation parts undo/redo management)
708           //if (aRes->isInHistory() && !aRes->isConcealed()) {
709             theResults.push_back(*aRIter);
710           //}
711         }
712       }
713     }
714   }
715 }
716
717
718 TDF_Label Model_Objects::featuresLabel() const
719 {
720   return myMain.FindChild(TAG_OBJECTS);
721 }
722
723 static std::string composeName(const std::string& theFeatureKind, const int theIndex)
724 {
725   std::stringstream aNameStream;
726   aNameStream << theFeatureKind << "_" << theIndex;
727   return aNameStream.str();
728 }
729
730 void Model_Objects::setUniqueName(FeaturePtr theFeature)
731 {
732   if (!theFeature->data()->name().empty())
733     return;  // not needed, name is already defined
734   std::string aName;  // result
735   // first count all features of such kind to start with index = count + 1
736   int aNumObjects = -1; // this feature is already in this map
737   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myFeatures);
738   for (; aFIter.More(); aFIter.Next()) {
739     if (aFIter.Value()->getKind() == theFeature->getKind())
740       aNumObjects++;
741   }
742   // generate candidate name
743   aName = composeName(theFeature->getKind(), aNumObjects + 1);
744   // check this is unique, if not, increase index by 1
745   for (aFIter.Initialize(myFeatures); aFIter.More();) {
746     FeaturePtr aFeature = aFIter.Value();
747     bool isSameName = aFeature->data()->name() == aName;
748     if (!isSameName) {  // check also results to avoid same results names (actual for Parts)
749       const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
750       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
751       for (; aRIter != aResults.cend(); aRIter++) {
752         isSameName = (*aRIter)->data()->name() == aName;
753       }
754     }
755
756     if (isSameName) {
757       aNumObjects++;
758       aName = composeName(theFeature->getKind(), aNumObjects + 1);
759       // reinitialize iterator to make sure a new name is unique
760       aFIter.Initialize(myFeatures);
761     } else
762       aFIter.Next();
763   }
764   theFeature->data()->setName(aName);
765 }
766
767 void Model_Objects::setUniqueName(FolderPtr theFolder)
768 {
769   if (!theFolder->name().empty())
770     return; // name is already defined
771
772   int aNbFolders = myFolders.Size();
773   std::string aName = composeName(ModelAPI_Folder::ID(), aNbFolders);
774
775   // check the uniqueness of the name
776   NCollection_DataMap<TDF_Label, ObjectPtr>::Iterator anIt(myFolders);
777   while (anIt.More()) {
778     if (anIt.Value()->data()->name() == aName) {
779       aName = composeName(ModelAPI_Folder::ID(), aNbFolders);
780       // reinitialize iterator to make sure a new name is unique
781       anIt.Initialize(myFolders);
782     } else
783       anIt.Next();
784   }
785
786   theFolder->data()->setName(aName);
787 }
788
789 void Model_Objects::initData(ObjectPtr theObj, TDF_Label theLab, const int theTag)
790 {
791   std::shared_ptr<Model_Data> aData(new Model_Data);
792   aData->setLabel(theLab.FindChild(theTag));
793   aData->setObject(theObj);
794   theObj->setDoc(myDoc);
795   theObj->setData(aData);
796   FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObj);
797   if (aFeature.get()) {
798     setUniqueName(aFeature);  // must be before "initAttributes" because duplicate part uses name
799   } else { // is it a folder?
800     FolderPtr aFolder = std::dynamic_pointer_cast<ModelAPI_Folder>(theObj);
801     if (aFolder)
802       setUniqueName(aFolder);
803   }
804   theObj->initAttributes();
805 }
806
807 std::shared_ptr<ModelAPI_Feature> Model_Objects::featureById(const int theId)
808 {
809   if (theId > 0) {
810     TDF_Label aLab = featuresLabel().FindChild(theId, Standard_False);
811     return feature(aLab);
812   }
813   return std::shared_ptr<ModelAPI_Feature>(); // not found
814 }
815
816 void Model_Objects::synchronizeFeatures(
817   const TDF_LabelList& theUpdated, const bool theUpdateReferences,
818   const bool theExecuteFeatures, const bool theOpen, const bool theFlush)
819 {
820   Model_Document* anOwner = std::dynamic_pointer_cast<Model_Document>(myDoc).get();
821   if (!anOwner) // this may happen on creation of document: nothing there, so nothing to synchronize
822     return;
823   // after all updates, sends a message that groups of features were created or updated
824   Events_Loop* aLoop = Events_Loop::loop();
825   static Events_ID aDispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
826   static Events_ID aCreateEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
827   static Events_ID anUpdateEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
828   static Events_ID aRedispEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
829   static Events_ID aDeleteEvent = Events_Loop::eventByName(EVENT_OBJECT_DELETED);
830   static Events_ID aToHideEvent = aLoop->eventByName(EVENT_OBJECT_TO_REDISPLAY);
831   bool isActive = aLoop->activateFlushes(false);
832
833   // collect all updated labels map
834   TDF_LabelMap anUpdatedMap;
835   TDF_ListIteratorOfLabelList anUpdatedIter(theUpdated);
836   for(; anUpdatedIter.More(); anUpdatedIter.Next()) {
837     TDF_Label& aFeatureLab = anUpdatedIter.Value();
838     while(aFeatureLab.Depth() > 3)
839       aFeatureLab = aFeatureLab.Father();
840     if (myFeatures.IsBound(aFeatureLab) || myFolders.IsBound(aFeatureLab))
841       anUpdatedMap.Add(aFeatureLab);
842   }
843
844   // update all objects by checking are they on labels or not
845   std::set<ObjectPtr> aNewFeatures, aKeptFeatures;
846   TDF_ChildIDIterator aLabIter(featuresLabel(), TDataStd_Comment::GetID());
847   for (; aLabIter.More(); aLabIter.Next()) {
848     TDF_Label aFeatureLabel = aLabIter.Value()->Label();
849     if (!myFeatures.IsBound(aFeatureLabel) && !myFolders.IsBound(aFeatureLabel)) {
850       // a new feature or folder is inserted
851
852       std::string aFeatureID = TCollection_AsciiString(Handle(TDataStd_Comment)::DownCast(
853                                aLabIter.Value())->Get()).ToCString();
854       bool isFolder = aFeatureID == ModelAPI_Folder::ID();
855
856       std::shared_ptr<Model_Session> aSession =
857           std::dynamic_pointer_cast<Model_Session>(ModelAPI_Session::get());
858
859       // create a feature
860       ObjectPtr aFeature = isFolder ? ObjectPtr(new ModelAPI_Folder)
861                                     : ObjectPtr(aSession->createFeature(aFeatureID, anOwner));
862       if (!aFeature.get()) {
863         // somethig is wrong, most probably, the opened document has invalid structure
864         Events_InfoMessage("Model_Objects", "Invalid type of object in the document").send();
865         aLabIter.Value()->Label().ForgetAllAttributes();
866         continue;
867       }
868       aFeature->init();
869       // this must be before "setData" to redo the sketch line correctly
870       if (isFolder)
871         myFolders.Bind(aFeatureLabel, aFeature);
872       else
873         myFeatures.Bind(aFeatureLabel, std::dynamic_pointer_cast<ModelAPI_Feature>(aFeature));
874       aNewFeatures.insert(aFeature);
875       initData(aFeature, aFeatureLabel, TAG_FEATURE_ARGUMENTS);
876       updateHistory(aFeature);
877
878       // event: model is updated
879       ModelAPI_EventCreator::get()->sendUpdated(aFeature, aCreateEvent);
880     } else {  // nothing is changed, both iterators are incremented
881       ObjectPtr anObject;
882       FeaturePtr aFeature;
883       if (myFeatures.Find(aFeatureLabel, aFeature)) {
884         aKeptFeatures.insert(aFeature);
885         anObject = aFeature;
886       } else
887         if (myFolders.Find(aFeatureLabel, anObject))
888           aKeptFeatures.insert(anObject);
889
890       if (anUpdatedMap.Contains(aFeatureLabel)) {
891         if (!theOpen) { // on abort/undo/redo reinitialize attributes if something is changed
892           std::list<std::shared_ptr<ModelAPI_Attribute> > anAttrs =
893             anObject->data()->attributes("");
894           std::list<std::shared_ptr<ModelAPI_Attribute> >::iterator anAttr = anAttrs.begin();
895           for(; anAttr != anAttrs.end(); anAttr++)
896             (*anAttr)->reinit();
897         }
898         ModelAPI_EventCreator::get()->sendUpdated(anObject, anUpdateEvent);
899         if (aFeature && aFeature->getKind() == "Parameter") {
900           // if parameters are changed, update the results (issue 937)
901           const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
902           std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
903           for (; aRIter != aResults.cend(); aRIter++) {
904             std::shared_ptr<ModelAPI_Result> aRes = *aRIter;
905             if (aRes->data()->isValid() && !aRes->isDisabled()) {
906               ModelAPI_EventCreator::get()->sendUpdated(aRes, anUpdateEvent);
907             }
908           }
909         }
910       }
911     }
912   }
913
914   // check all features are checked: if not => it was removed
915   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myFeatures);
916   while (aFIter.More()) {
917     if (aKeptFeatures.find(aFIter.Value()) == aKeptFeatures.end()
918       && aNewFeatures.find(aFIter.Value()) == aNewFeatures.end()) {
919         FeaturePtr aFeature = aFIter.Value();
920         // event: model is updated
921         //if (aFeature->isInHistory()) {
922         ModelAPI_EventCreator::get()->sendDeleted(myDoc, ModelAPI_Feature::group());
923         //}
924         // results of this feature must be redisplayed (hided)
925         // redisplay also removed feature (used for sketch and AISObject)
926         ModelAPI_EventCreator::get()->sendUpdated(aFeature, aRedispEvent);
927         updateHistory(aFeature);
928         aFeature->erase();
929
930         // unbind after the "erase" call: on abort sketch
931         // is removes sub-objects that corrupts aFIter
932         myFeatures.UnBind(aFIter.Key());
933         // reinitialize iterator because unbind may corrupt the previous order in the map
934         aFIter.Initialize(myFeatures);
935     } else
936       aFIter.Next();
937   }
938   // verify folders are checked: if not => is was removed
939   for (NCollection_DataMap<TDF_Label, ObjectPtr>::Iterator aFldIt(myFolders);
940        aFldIt.More(); aFldIt.Next()) {
941     ObjectPtr aCurObj = aFldIt.Value();
942     if (aKeptFeatures.find(aCurObj) == aKeptFeatures.end() &&
943         aNewFeatures.find(aCurObj) == aNewFeatures.end()) {
944       ModelAPI_EventCreator::get()->sendDeleted(myDoc, ModelAPI_Folder::group());
945       // results of this feature must be redisplayed (hided)
946       // redisplay also removed feature (used for sketch and AISObject)
947       ModelAPI_EventCreator::get()->sendUpdated(aCurObj, aRedispEvent);
948       updateHistory(aCurObj);
949       aCurObj->erase();
950
951       // unbind after the "erase" call: on abort sketch
952       // is removes sub-objects that corrupts aFIter
953       myFolders.UnBind(aFldIt.Key());
954       // reinitialize iterator because unbind may corrupt the previous order in the map
955       aFldIt.Initialize(myFolders);
956     }
957   }
958
959   if (theUpdateReferences) {
960     synchronizeBackRefs();
961   }
962   // update results of the features (after features created because
963   // they may be connected, like sketch and sub elements)
964   // After synchronisation of back references because sketch
965   // must be set in sub-elements before "execute" by updateResults
966   std::set<FeaturePtr> aProcessed; // composites must be updated after their subs (issue 360)
967   TDF_ChildIDIterator aLabIter2(featuresLabel(), TDataStd_Comment::GetID());
968   for (; aLabIter2.More(); aLabIter2.Next()) {
969     TDF_Label aFeatureLabel = aLabIter2.Value()->Label();
970     if (myFeatures.IsBound(aFeatureLabel)) {  // a new feature is inserted
971       FeaturePtr aFeature = myFeatures.Find(aFeatureLabel);
972       updateResults(aFeature, aProcessed);
973     }
974   }
975   // the synchronize should be done after updateResults
976   // in order to correct back references of updated results
977   if (theUpdateReferences) {
978     synchronizeBackRefs();
979   }
980   if (!theUpdated.IsEmpty()) {
981     // this means there is no control what was modified => remove history cash
982     myHistory.clear();
983   }
984
985   if (!theExecuteFeatures)
986     anOwner->setExecuteFeatures(false);
987   aLoop->activateFlushes(isActive);
988
989   if (theFlush) {
990     aLoop->flush(aDeleteEvent);
991     // delete should be emitted before create to reacts to aborted feature
992     aLoop->flush(aCreateEvent);
993     aLoop->flush(anUpdateEvent);
994     aLoop->flush(aCreateEvent); // after update of features, there could be results created
995     aLoop->flush(aDeleteEvent); // or deleted
996     aLoop->flush(aRedispEvent);
997     aLoop->flush(aToHideEvent);
998   }
999   if (!theExecuteFeatures)
1000     anOwner->setExecuteFeatures(true);
1001 }
1002
1003 /// synchronises back references for the given object basing on the collected data
1004 void Model_Objects::synchronizeBackRefsForObject(const std::set<AttributePtr>& theNewRefs,
1005   ObjectPtr theObject)
1006 {
1007   if (!theObject.get() || !theObject->data()->isValid())
1008     return; // invalid
1009   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(theObject->data());
1010   // iterate new list to compare with curent
1011   std::set<AttributePtr>::iterator aNewIter = theNewRefs.begin();
1012   for(; aNewIter != theNewRefs.end(); aNewIter++) {
1013     if (aData->refsToMe().find(*aNewIter) == aData->refsToMe().end()) {
1014       FeaturePtr aRefFeat = std::dynamic_pointer_cast<ModelAPI_Feature>((*aNewIter)->owner());
1015       if (aRefFeat)
1016         aData->addBackReference(aRefFeat, (*aNewIter)->id());
1017       else // add back reference to a folder
1018         aData->addBackReference((*aNewIter)->owner(), (*aNewIter)->id());
1019     }
1020   }
1021   if (theNewRefs.size() != aData->refsToMe().size()) { // some back ref must be removed
1022     std::set<AttributePtr>::iterator aCurrentIter = aData->refsToMe().begin();
1023     while(aCurrentIter != aData->refsToMe().end()) {
1024       if (theNewRefs.find(*aCurrentIter) == theNewRefs.end()) {
1025         // for external references from other documents this system
1026         // is not working: refs are collected from
1027         // different Model_Objects, so before remove check this
1028         // external object exists and still referenced
1029         bool aLeaveIt = false;
1030         if ((*aCurrentIter)->owner().get() && (*aCurrentIter)->owner()->document() != myDoc &&
1031             (*aCurrentIter)->owner()->data().get() && (*aCurrentIter)->owner()->data()->isValid()) {
1032           std::list<std::pair<std::string, std::list<std::shared_ptr<ModelAPI_Object> > > > aRefs;
1033           (*aCurrentIter)->owner()->data()->referencesToObjects(aRefs);
1034           std::list<std::pair<std::string, std::list<std::shared_ptr<ModelAPI_Object> >>>::iterator
1035             aRefIter = aRefs.begin();
1036           for(; aRefIter != aRefs.end(); aRefIter++) {
1037             if ((*aCurrentIter)->id() == aRefIter->first) {
1038               std::list<std::shared_ptr<ModelAPI_Object> >::iterator anOIt;
1039               for(anOIt = aRefIter->second.begin(); anOIt != aRefIter->second.end(); anOIt++) {
1040                 if (*anOIt == theObject) {
1041                   aLeaveIt = true;
1042                 }
1043               }
1044             }
1045           }
1046         }
1047         if (!aLeaveIt) {
1048           aData->removeBackReference(*aCurrentIter);
1049           aCurrentIter = aData->refsToMe().begin(); // reinitialize iteration after delete
1050         } else aCurrentIter++;
1051       } else aCurrentIter++;
1052     }
1053   }
1054   // for the last feature in the folder, check if it is a sub-feature,
1055   // then refer the folder to a top-level parent composite feature
1056   const std::set<AttributePtr>& aRefs = aData->refsToMe();
1057   std::set<AttributePtr>::iterator anIt = aRefs.begin();
1058   for (; anIt != aRefs.end(); ++anIt)
1059     if ((*anIt)->id() == ModelAPI_Folder::LAST_FEATURE_ID())
1060       break;
1061   if (anIt != aRefs.end()) {
1062     FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
1063     if (aFeature) {
1064       CompositeFeaturePtr aParent;
1065       CompositeFeaturePtr aGrandParent = ModelAPI_Tools::compositeOwner(aFeature);
1066       do {
1067         aParent = aGrandParent;
1068         if (aGrandParent)
1069           aGrandParent = ModelAPI_Tools::compositeOwner(aParent);
1070       } while (aGrandParent.get());
1071       if (aParent) {
1072         ObjectPtr aFolder = (*anIt)->owner();
1073         // remove reference from the current feature
1074         aData->removeBackReference(aFolder, ModelAPI_Folder::LAST_FEATURE_ID());
1075         // set reference to a top-level parent
1076         aFolder->data()->reference(ModelAPI_Folder::LAST_FEATURE_ID())->setValue(aParent);
1077         std::shared_ptr<Model_Data> aParentData =
1078             std::dynamic_pointer_cast<Model_Data>(aParent->data());
1079         aParentData->addBackReference(aFolder, ModelAPI_Folder::LAST_FEATURE_ID());
1080       }
1081     }
1082   }
1083   aData->updateConcealmentFlag();
1084 }
1085
1086 static void collectReferences(std::shared_ptr<ModelAPI_Data> theData,
1087                               std::map<ObjectPtr, std::set<AttributePtr> >& theRefs)
1088 {
1089   if (theData.get()) {
1090     std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
1091     theData->referencesToObjects(aRefs);
1092     std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator aRefsIt = aRefs.begin();
1093     for(; aRefsIt != aRefs.end(); aRefsIt++) {
1094       std::list<ObjectPtr>::iterator aRefTo = aRefsIt->second.begin();
1095       for(; aRefTo != aRefsIt->second.end(); aRefTo++) {
1096         if (*aRefTo) {
1097           std::map<ObjectPtr, std::set<AttributePtr> >::iterator aFound = theRefs.find(*aRefTo);
1098           if (aFound == theRefs.end()) {
1099             theRefs[*aRefTo] = std::set<AttributePtr>();
1100             aFound = theRefs.find(*aRefTo);
1101           }
1102           aFound->second.insert(theData->attribute(aRefsIt->first));
1103         }
1104       }
1105     }
1106   }
1107 }
1108
1109 void Model_Objects::synchronizeBackRefs()
1110 {
1111   // collect all back references in the separated container: to update everything at once,
1112   // without additional Concealment switchin on and off: only the final modification
1113
1114   // referenced (slave) objects to referencing attirbutes
1115   std::map<ObjectPtr, std::set<AttributePtr> > allRefs;
1116   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFeatures(myFeatures);
1117   for(; aFeatures.More(); aFeatures.Next()) {
1118     FeaturePtr aFeature = aFeatures.Value();
1119     collectReferences(aFeature->data(), allRefs);
1120   }
1121   NCollection_DataMap<TDF_Label, ObjectPtr>::Iterator aFolders(myFolders);
1122   for(; aFolders.More(); aFolders.Next()) {
1123     ObjectPtr aFolder = aFolders.Value();
1124     collectReferences(aFolder->data(), allRefs);
1125   }
1126   // second iteration: just compare back-references with existing in features and results
1127   for(aFeatures.Initialize(myFeatures); aFeatures.More(); aFeatures.Next()) {
1128     FeaturePtr aFeature = aFeatures.Value();
1129     static std::set<AttributePtr> anEmpty;
1130     std::map<ObjectPtr, std::set<AttributePtr> >::iterator aFound = allRefs.find(aFeature);
1131     if (aFound == allRefs.end()) { // not found => erase all back references
1132       synchronizeBackRefsForObject(anEmpty, aFeature);
1133     } else {
1134       synchronizeBackRefsForObject(aFound->second, aFeature);
1135       allRefs.erase(aFound); // to check that all refs are counted
1136     }
1137     // also for results
1138     std::list<ResultPtr> aResults;
1139     ModelAPI_Tools::allResults(aFeature, aResults);
1140     std::list<ResultPtr>::iterator aRIter = aResults.begin();
1141     for(; aRIter != aResults.cend(); aRIter++) {
1142       aFound = allRefs.find(*aRIter);
1143       if (aFound == allRefs.end()) { // not found => erase all back references
1144         synchronizeBackRefsForObject(anEmpty, *aRIter);
1145       } else {
1146         synchronizeBackRefsForObject(aFound->second, *aRIter);
1147         allRefs.erase(aFound); // to check that all refs are counted
1148       }
1149     }
1150   }
1151   for(aFeatures.Initialize(myFeatures); aFeatures.More(); aFeatures.Next()) {
1152     FeaturePtr aFeature = aFeatures.Value();
1153     std::list<ResultPtr> aResults;
1154     ModelAPI_Tools::allResults(aFeature, aResults);
1155     // update the concealment status for disply in isConcealed of ResultBody
1156     std::list<ResultPtr>::iterator aRIter = aResults.begin();
1157     for(; aRIter != aResults.cend(); aRIter++) {
1158       (*aRIter)->isConcealed();
1159     }
1160   }
1161   // the rest all refs means that feature references to the external document feature:
1162   // process also them
1163   std::map<ObjectPtr, std::set<AttributePtr> >::iterator anExtIter = allRefs.begin();
1164   for(; anExtIter != allRefs.end(); anExtIter++) {
1165     synchronizeBackRefsForObject(anExtIter->second, anExtIter->first);
1166   }
1167 }
1168
1169 TDF_Label Model_Objects::resultLabel(
1170   const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theResultIndex)
1171 {
1172   const std::shared_ptr<Model_Data>& aData =
1173     std::dynamic_pointer_cast<Model_Data>(theFeatureData);
1174   return aData->label().Father().FindChild(TAG_FEATURE_RESULTS).FindChild(theResultIndex + 1);
1175 }
1176
1177 bool Model_Objects::hasCustomName(DataPtr theFeatureData,
1178                                   ResultPtr theResult,
1179                                   int theResultIndex,
1180                                   std::string& theParentName) const
1181 {
1182   ResultBodyPtr aBodyRes = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theFeatureData->owner());
1183   if (aBodyRes && std::dynamic_pointer_cast<Model_Data>(theFeatureData)->label().Depth() < 7) {
1184     // only for top-results (works for the cases when results are not yet added to the feature)
1185     FeaturePtr anOwner = ModelAPI_Feature::feature(theResult);
1186
1187     // names of sub-solids in CompSolid should be default (for example,
1188     // result of boolean operation 'Boolean_1' is a CompSolid which is renamed to 'MyBOOL',
1189     // however, sub-elements of 'MyBOOL' should be named 'Boolean_1_1', 'Boolean_1_2' etc.)
1190     std::ostringstream aDefaultName;
1191     aDefaultName << anOwner->name();
1192     // compute default name of CompSolid (name of feature + index of CompSolid's result)
1193     int aBodyResultIndex = 0;
1194     const std::list<ResultPtr>& aResults = anOwner->results();
1195     std::list<ResultPtr>::const_iterator anIt = aResults.begin();
1196     for(; anIt != aResults.end(); ++anIt, ++aBodyResultIndex)
1197       if(aBodyRes == *anIt)
1198         break;
1199     aDefaultName << "_" << (aBodyResultIndex + 1);
1200     theParentName = aDefaultName.str();
1201     return false;
1202   }
1203
1204   std::pair<std::string, bool> aName = ModelAPI_Tools::getDefaultName(theResult);
1205   if (aName.second)
1206     theParentName = aName.first;
1207   return aName.second;
1208 }
1209
1210 void Model_Objects::storeResult(std::shared_ptr<ModelAPI_Data> theFeatureData,
1211                                 std::shared_ptr<ModelAPI_Result> theResult,
1212                                 const int theResultIndex)
1213 {
1214   theResult->init();
1215   theResult->setDoc(myDoc);
1216   initData(theResult, resultLabel(theFeatureData, theResultIndex), TAG_FEATURE_ARGUMENTS);
1217   if (theResult->data()->name().empty()) {
1218     // if was not initialized, generate event and set a name
1219     std::string aNewName = theFeatureData->name();
1220     if (hasCustomName(theFeatureData, theResult, theResultIndex, aNewName)) {
1221       // if the name of result is user-defined, then, at first time, assign name of the result
1222       // by empty string to be sure that corresponding flag in the data model is set
1223       theResult->data()->setName("");
1224     } else {
1225       std::stringstream aName;
1226       aName << aNewName;
1227       // if there are several results (issue #899: any number of result),
1228       // add unique prefix starting from second
1229       if (theResultIndex > 0 || theResult->groupName() == ModelAPI_ResultBody::group())
1230         aName << "_" << theResultIndex + 1;
1231       aNewName = aName.str();
1232     }
1233     theResult->data()->setName(aNewName);
1234   }
1235 }
1236
1237 std::shared_ptr<ModelAPI_ResultConstruction> Model_Objects::createConstruction(
1238     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1239 {
1240   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1241   TDataStd_Comment::Set(aLab, ModelAPI_ResultConstruction::group().c_str());
1242   ObjectPtr anOldObject = object(aLab);
1243   std::shared_ptr<ModelAPI_ResultConstruction> aResult;
1244   if (anOldObject.get()) {
1245     aResult = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(anOldObject);
1246   }
1247   if (!aResult.get()) {
1248     aResult = std::shared_ptr<ModelAPI_ResultConstruction>(new Model_ResultConstruction);
1249     storeResult(theFeatureData, aResult, theIndex);
1250   }
1251   return aResult;
1252 }
1253
1254 std::shared_ptr<ModelAPI_ResultBody> Model_Objects::createBody(
1255     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1256 {
1257   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1258   TDataStd_Comment::Set(aLab, ModelAPI_ResultBody::group().c_str());
1259   ObjectPtr anOldObject = object(aLab);
1260   std::shared_ptr<ModelAPI_ResultBody> aResult;
1261   if (anOldObject.get()) {
1262     aResult = std::dynamic_pointer_cast<ModelAPI_ResultBody>(anOldObject);
1263   }
1264   if (!aResult.get()) {
1265     aResult = std::shared_ptr<ModelAPI_ResultBody>(new Model_ResultBody);
1266     storeResult(theFeatureData, aResult, theIndex);
1267   }
1268   return aResult;
1269 }
1270
1271 std::shared_ptr<ModelAPI_ResultPart> Model_Objects::createPart(
1272     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1273 {
1274   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1275   TDataStd_Comment::Set(aLab, ModelAPI_ResultPart::group().c_str());
1276   ObjectPtr anOldObject = object(aLab);
1277   std::shared_ptr<ModelAPI_ResultPart> aResult;
1278   if (anOldObject.get()) {
1279     aResult = std::dynamic_pointer_cast<ModelAPI_ResultPart>(anOldObject);
1280   }
1281   if (!aResult.get()) {
1282     aResult = std::shared_ptr<ModelAPI_ResultPart>(new Model_ResultPart);
1283     storeResult(theFeatureData, aResult, theIndex);
1284   }
1285   return aResult;
1286 }
1287
1288 std::shared_ptr<ModelAPI_ResultPart> Model_Objects::copyPart(
1289     const std::shared_ptr<ModelAPI_ResultPart>& theOrigin,
1290     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1291 {
1292   std::shared_ptr<ModelAPI_ResultPart> aResult = createPart(theFeatureData, theIndex);
1293   aResult->data()->reference(Model_ResultPart::BASE_REF_ID())->setValue(theOrigin);
1294   return aResult;
1295 }
1296
1297 std::shared_ptr<ModelAPI_ResultGroup> Model_Objects::createGroup(
1298     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1299 {
1300   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1301   TDataStd_Comment::Set(aLab, ModelAPI_ResultGroup::group().c_str());
1302   ObjectPtr anOldObject = object(aLab);
1303   std::shared_ptr<ModelAPI_ResultGroup> aResult;
1304   if (anOldObject.get()) {
1305     aResult = std::dynamic_pointer_cast<ModelAPI_ResultGroup>(anOldObject);
1306   }
1307   if (!aResult.get()) {
1308     aResult = std::shared_ptr<ModelAPI_ResultGroup>(new Model_ResultGroup(theFeatureData));
1309     storeResult(theFeatureData, aResult, theIndex);
1310   }
1311   return aResult;
1312 }
1313
1314 std::shared_ptr<ModelAPI_ResultField> Model_Objects::createField(
1315     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1316 {
1317   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1318   TDataStd_Comment::Set(aLab, ModelAPI_ResultField::group().c_str());
1319   ObjectPtr anOldObject = object(aLab);
1320   std::shared_ptr<ModelAPI_ResultField> aResult;
1321   if (anOldObject.get()) {
1322     aResult = std::dynamic_pointer_cast<ModelAPI_ResultField>(anOldObject);
1323   }
1324   if (!aResult.get()) {
1325     aResult = std::shared_ptr<ModelAPI_ResultField>(new Model_ResultField(theFeatureData));
1326     storeResult(theFeatureData, aResult, theIndex);
1327   }
1328   return aResult;
1329 }
1330
1331 std::shared_ptr<ModelAPI_ResultParameter> Model_Objects::createParameter(
1332       const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1333 {
1334   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1335   TDataStd_Comment::Set(aLab, ModelAPI_ResultParameter::group().c_str());
1336   ObjectPtr anOldObject = object(aLab);
1337   std::shared_ptr<ModelAPI_ResultParameter> aResult;
1338   if (anOldObject.get()) {
1339     aResult = std::dynamic_pointer_cast<ModelAPI_ResultParameter>(anOldObject);
1340   }
1341   if (!aResult.get()) {
1342     aResult = std::shared_ptr<ModelAPI_ResultParameter>(new Model_ResultParameter);
1343     storeResult(theFeatureData, aResult, theIndex);
1344   }
1345   return aResult;
1346 }
1347
1348 std::shared_ptr<ModelAPI_Folder> Model_Objects::createFolder(
1349     const std::shared_ptr<ModelAPI_Feature>& theBeforeThis)
1350 {
1351   FolderPtr aFolder(new ModelAPI_Folder);
1352   if (!aFolder)
1353     return aFolder;
1354
1355   TDF_Label aFeaturesLab = featuresLabel();
1356   TDF_Label aFolderLab = aFeaturesLab.NewChild();
1357   // store feature in the features array: before "initData" because in macro features
1358   // in initData it creates new features, appeared later than this
1359   TDF_Label aPrevFeatureLab;
1360   if (theBeforeThis.get()) { // searching for the previous feature label
1361     std::shared_ptr<Model_Data> aPrevData =
1362         std::dynamic_pointer_cast<Model_Data>(theBeforeThis->data());
1363     if (aPrevData.get()) {
1364       aPrevFeatureLab = nextLabel(aPrevData->label().Father(), true);
1365     }
1366   } else { // find the label of the last feature
1367     Handle(TDataStd_ReferenceArray) aRefs;
1368     if (aFeaturesLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
1369       aPrevFeatureLab = aRefs->Value(aRefs->Upper());
1370   }
1371   AddToRefArray(aFeaturesLab, aFolderLab, aPrevFeatureLab);
1372
1373   // keep the feature ID to restore document later correctly
1374   TDataStd_Comment::Set(aFolderLab, ModelAPI_Folder::ID().c_str());
1375   myFolders.Bind(aFolderLab, aFolder);
1376   // must be before the event sending: for OB the feature is already added
1377   updateHistory(ModelAPI_Folder::group());
1378   updateHistory(ModelAPI_Feature::group());
1379
1380   // must be after binding to the map because of "Box" macro feature that
1381   // creates other features in "initData"
1382   initData(aFolder, aFolderLab, TAG_FEATURE_ARGUMENTS);
1383   // event: folder is added, must be before "initData" to update OB correctly on Duplicate:
1384   // first new part, then the content
1385   static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
1386   ModelAPI_EventCreator::get()->sendUpdated(aFolder, anEvent);
1387
1388   return aFolder;
1389 }
1390
1391 void Model_Objects::removeFolder(std::shared_ptr<ModelAPI_Folder> theFolder)
1392 {
1393   std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theFolder->data());
1394   if (!aData.get() || !aData->isValid())
1395     return;
1396
1397   // this must be before erase since theFolder erasing removes all information about it
1398   clearHistory(theFolder);
1399   // erase fields
1400   theFolder->erase();
1401
1402   TDF_Label aFolderLabel = aData->label().Father();
1403   if (myFolders.IsBound(aFolderLabel))
1404     myFolders.UnBind(aFolderLabel);
1405
1406   static Events_ID EVENT_DISP = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
1407   ModelAPI_EventCreator::get()->sendUpdated(theFolder, EVENT_DISP);
1408   // erase all attributes under the label of feature
1409   aFolderLabel.ForgetAllAttributes();
1410   // remove it from the references array
1411   RemoveFromRefArray(featuresLabel(), aFolderLabel);
1412   // event: feature is deleted
1413   ModelAPI_EventCreator::get()->sendDeleted(theFolder->document(), ModelAPI_Folder::group());
1414   updateHistory(ModelAPI_Folder::group());
1415   updateHistory(ModelAPI_Feature::group());
1416 }
1417
1418 // Returns one of the limiting features of the list
1419 static FeaturePtr limitingFeature(std::list<FeaturePtr>& theFeatures, const bool isLast)
1420 {
1421   FeaturePtr aFeature;
1422   if (isLast) {
1423     aFeature = theFeatures.back();
1424     theFeatures.pop_back();
1425   } else {
1426     aFeature = theFeatures.front();
1427     theFeatures.pop_front();
1428   }
1429   return aFeature;
1430 }
1431
1432 // Verify the feature is sub-element in composite feature or it is not used in the history
1433 static bool isSkippedFeature(FeaturePtr theFeature)
1434 {
1435   bool isSub = ModelAPI_Tools::compositeOwner(theFeature).get() != NULL;
1436   return isSub || (theFeature && !theFeature->isInHistory());
1437 }
1438
1439 std::shared_ptr<ModelAPI_Folder> Model_Objects::findFolder(
1440       const std::list<std::shared_ptr<ModelAPI_Feature> >& theFeatures,
1441       const bool theBelow)
1442 {
1443   if (theFeatures.empty())
1444     return FolderPtr(); // nothing to move
1445
1446   TDF_Label aFeaturesLab = featuresLabel();
1447   Handle(TDataStd_ReferenceArray) aRefs;
1448   if (!aFeaturesLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
1449     return FolderPtr(); // no reference array (something is wrong)
1450
1451   std::list<std::shared_ptr<ModelAPI_Feature> > aFeatures = theFeatures;
1452   std::shared_ptr<ModelAPI_Feature> aLimitingFeature = limitingFeature(aFeatures, theBelow);
1453
1454   std::shared_ptr<Model_Data> aData =
1455       std::static_pointer_cast<Model_Data>(aLimitingFeature->data());
1456   if (!aData || !aData->isValid())
1457     return FolderPtr(); // invalid feature
1458
1459   // label of the first feature in the list for fast searching
1460   TDF_Label aFirstFeatureLabel = aData->label().Father();
1461
1462   // find a folder above the features and
1463   // check the given features represent a sequential list of objects following the folder
1464   FolderPtr aFoundFolder;
1465   TDF_Label aLastFeatureInFolder;
1466   int aRefIndex = aRefs->Lower();
1467   for(; aRefIndex <= aRefs->Upper(); ++aRefIndex) { // iterate all existing features
1468     TDF_Label aCurLabel = aRefs->Value(aRefIndex);
1469     if (IsEqual(aCurLabel, aFirstFeatureLabel))
1470       break; // no need to continue searching
1471
1472     // searching the folder below, just continue to search last feature from the list
1473     if (theBelow)
1474       continue;
1475
1476     // if feature is in sub-component, skip it
1477     FeaturePtr aCurFeature = feature(aCurLabel);
1478     if (isSkippedFeature(aCurFeature))
1479       continue;
1480
1481     if (!aLastFeatureInFolder.IsNull()) {
1482       if (IsEqual(aCurLabel, aLastFeatureInFolder))
1483         aLastFeatureInFolder.Nullify(); // the last feature in the folder is achived
1484       continue;
1485     }
1486
1487     const ObjectPtr& aFolderObj = folder(aCurLabel);
1488     if (aFolderObj.get()) {
1489       aFoundFolder = std::dynamic_pointer_cast<ModelAPI_Folder>(aFolderObj);
1490       AttributeReferencePtr aLastFeatAttr =
1491           aFoundFolder->reference(ModelAPI_Folder::LAST_FEATURE_ID());
1492       if (aLastFeatAttr) {
1493         // setup iterating inside a folder to find last feature
1494         ObjectPtr aLastFeature = aLastFeatAttr->value();
1495         if (aLastFeature) {
1496           aData = std::static_pointer_cast<Model_Data>(aLastFeature->data());
1497           if (aData && aData->isValid())
1498             aLastFeatureInFolder = aData->label().Father();
1499         }
1500       }
1501     }
1502   }
1503
1504   if (theBelow && aRefIndex < aRefs->Upper()) {
1505     TDF_Label aLabel;
1506     // skip following features which are sub-components or not in history
1507     for (int anIndex = aRefIndex + 1; anIndex <= aRefs->Upper(); ++anIndex) {
1508       aLabel = aRefs->Value(anIndex);
1509       FeaturePtr aCurFeature = feature(aLabel);
1510       if (!isSkippedFeature(aCurFeature))
1511         break;
1512     }
1513     // check the next object is a folder
1514     aFoundFolder = std::dynamic_pointer_cast<ModelAPI_Folder>(folder(aLabel));
1515   }
1516
1517   if (!aLastFeatureInFolder.IsNull() || // the last feature of the folder above is not found
1518       !aFoundFolder)
1519     return FolderPtr();
1520
1521   // check the given features are sequential list
1522   int aStep = theBelow ? -1 : 1;
1523   for (aRefIndex += aStep;
1524        !aFeatures.empty() && aRefIndex >= aRefs->Lower() && aRefIndex <= aRefs->Upper();
1525        aRefIndex += aStep) {
1526     TDF_Label aCurLabel = aRefs->Value(aRefIndex);
1527     // if feature is in sub-component, skip it
1528     FeaturePtr aCurFeature = feature(aCurLabel);
1529     if (isSkippedFeature(aCurFeature))
1530       continue;
1531
1532     aLimitingFeature = limitingFeature(aFeatures, theBelow);
1533     if (!aCurFeature->data()->isEqual(aLimitingFeature->data()))
1534       return FolderPtr(); // not a sequential list
1535   }
1536
1537   return aFoundFolder;
1538 }
1539
1540 bool Model_Objects::moveToFolder(
1541       const std::list<std::shared_ptr<ModelAPI_Feature> >& theFeatures,
1542       const std::shared_ptr<ModelAPI_Folder>& theFolder)
1543 {
1544   if (theFeatures.empty() || !theFolder)
1545     return false;
1546
1547   // labels for the folder and last feature in the list
1548   TDF_Label aFolderLabel, aLastFeatureLabel;
1549   std::shared_ptr<Model_Data> aData =
1550       std::static_pointer_cast<Model_Data>(theFolder->data());
1551   if (aData && aData->isValid())
1552     aFolderLabel = aData->label().Father();
1553   aData = std::static_pointer_cast<Model_Data>(theFeatures.back()->data());
1554   if (aData && aData->isValid())
1555     aLastFeatureLabel = aData->label().Father();
1556
1557   if (aFolderLabel.IsNull() || aLastFeatureLabel.IsNull())
1558     return false;
1559
1560   AttributeReferencePtr aFirstFeatAttr =
1561       theFolder->reference(ModelAPI_Folder::FIRST_FEATURE_ID());
1562   AttributeReferencePtr aLastFeatAttr =
1563       theFolder->reference(ModelAPI_Folder::LAST_FEATURE_ID());
1564   bool initFirstAttr = !aFirstFeatAttr->value().get();
1565   bool initLastAttr  = !aLastFeatAttr->value().get();
1566
1567   // check the folder is below the list of features
1568   bool isFolderBelow = false;
1569   TDF_Label aFeaturesLab = featuresLabel();
1570   Handle(TDataStd_ReferenceArray) aRefs;
1571   if (!aFeaturesLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
1572     return false; // no reference array (something is wrong)
1573   for (int aRefIndex = aRefs->Lower(); aRefIndex <= aRefs->Upper(); ++aRefIndex) {
1574     TDF_Label aCurLabel = aRefs->Value(aRefIndex);
1575     if (aCurLabel == aFolderLabel)
1576       break; // folder is above the features
1577     else if (aCurLabel == aLastFeatureLabel) {
1578       isFolderBelow = true;
1579       break;
1580     }
1581   }
1582
1583   if (isFolderBelow) {
1584     aData = std::static_pointer_cast<Model_Data>(theFeatures.front()->data());
1585     if (!aData || !aData->isValid())
1586       return false;
1587     TDF_Label aPrevFeatureLabel = aData->label().Father();
1588     // label of the feature before the first feature in the list
1589     for (int aRefIndex = aRefs->Lower(); aRefIndex <= aRefs->Upper(); ++aRefIndex)
1590       if (aPrevFeatureLabel == aRefs->Value(aRefIndex)) {
1591         if (aRefIndex == aRefs->Lower())
1592           aPrevFeatureLabel.Nullify();
1593         else
1594           aPrevFeatureLabel = aRefs->Value(aRefIndex - 1);
1595         break;
1596       }
1597
1598     // move the folder in the list of references before the first feature
1599     RemoveFromRefArray(aFeaturesLab, aFolderLabel);
1600     AddToRefArray(aFeaturesLab, aFolderLabel, aPrevFeatureLabel);
1601     // update first feature of the folder
1602     initFirstAttr = true;
1603   } else {
1604     // update last feature of the folder
1605     initLastAttr = true;
1606   }
1607
1608   if (initFirstAttr)
1609     aFirstFeatAttr->setValue(theFeatures.front());
1610   if (initLastAttr)
1611     aLastFeatAttr->setValue(theFeatures.back());
1612
1613   updateHistory(ModelAPI_Feature::group());
1614   return true;
1615 }
1616
1617 static FolderPtr isExtractionCorrect(const FolderPtr& theFirstFeatureFolder,
1618                                      const FolderPtr& theLastFeatureFolder,
1619                                      bool& isExtractBefore)
1620 {
1621   if (theFirstFeatureFolder.get()) {
1622     if (theLastFeatureFolder.get())
1623       return theFirstFeatureFolder == theLastFeatureFolder ? theFirstFeatureFolder : FolderPtr();
1624     else
1625       isExtractBefore = true;
1626     return theFirstFeatureFolder;
1627   } else if (theLastFeatureFolder.get()) {
1628     isExtractBefore = false;
1629     return theLastFeatureFolder;
1630   }
1631   // no folder found
1632   return FolderPtr();
1633 }
1634
1635 bool Model_Objects::removeFromFolder(
1636       const std::list<std::shared_ptr<ModelAPI_Feature> >& theFeatures,
1637       const bool theBefore)
1638 {
1639   if (theFeatures.empty())
1640     return false;
1641
1642   FolderPtr aFirstFeatureFolder =
1643       inFolder(theFeatures.front(), ModelAPI_Folder::FIRST_FEATURE_ID());
1644   FolderPtr aLastFeatureFolder =
1645       inFolder(theFeatures.back(),  ModelAPI_Folder::LAST_FEATURE_ID());
1646
1647   bool isExtractBeforeFolder = theBefore;
1648   FolderPtr aFoundFolder =
1649       isExtractionCorrect(aFirstFeatureFolder, aLastFeatureFolder, isExtractBeforeFolder);
1650   if (!aFoundFolder)
1651     return false; // list of features cannot be extracted
1652
1653   // references of the current folder
1654   ObjectPtr aFolderStartFeature;
1655   ObjectPtr aFolderEndFeature;
1656   if (aFirstFeatureFolder != aLastFeatureFolder) {
1657     aFolderStartFeature = aFoundFolder->reference(ModelAPI_Folder::FIRST_FEATURE_ID())->value();
1658     aFolderEndFeature   = aFoundFolder->reference(ModelAPI_Folder::LAST_FEATURE_ID())->value();
1659   }
1660
1661   FeaturePtr aFeatureToFind = isExtractBeforeFolder ? theFeatures.back() : theFeatures.front();
1662   std::shared_ptr<Model_Data> aData =
1663       std::static_pointer_cast<Model_Data>(aFeatureToFind->data());
1664   if (!aData || !aData->isValid())
1665     return false;
1666   TDF_Label aLabelToFind = aData->label().Father();
1667
1668   // search the label in the list of references
1669   TDF_Label aFeaturesLab = featuresLabel();
1670   Handle(TDataStd_ReferenceArray) aRefs;
1671   if (!aFeaturesLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
1672     return false; // no reference array (something is wrong)
1673   int aRefIndex = aRefs->Lower();
1674   for (; aRefIndex <= aRefs->Upper(); ++aRefIndex)
1675     if (aRefs->Value(aRefIndex) == aLabelToFind)
1676       break;
1677
1678   // update folder position
1679   if (isExtractBeforeFolder) {
1680     aData = std::dynamic_pointer_cast<Model_Data>(aFoundFolder->data());
1681     TDF_Label aFolderLabel = aData->label().Father();
1682     TDF_Label aPrevFeatureLabel = aRefs->Value(aRefIndex);
1683     // update start reference of the folder
1684     if (aFolderStartFeature.get()) {
1685       FeaturePtr aNewStartFeature;
1686       do { // skip all features placed in the composite features
1687         aPrevFeatureLabel = aRefs->Value(aRefIndex++);
1688         aNewStartFeature =
1689             aRefIndex <= aRefs->Upper() ? feature(aRefs->Value(aRefIndex)) : FeaturePtr();
1690       } while (aNewStartFeature && isSkippedFeature(aNewStartFeature));
1691       aFolderStartFeature = aNewStartFeature;
1692     }
1693     // move the folder in the list of references after the last feature from the list
1694     RemoveFromRefArray(aFeaturesLab, aFolderLabel);
1695     AddToRefArray(aFeaturesLab, aFolderLabel, aPrevFeatureLabel);
1696   } else {
1697     // update end reference of the folder
1698     if (aFolderEndFeature.get()) {
1699       FeaturePtr aNewEndFeature;
1700       do { // skip all features placed in the composite features
1701         --aRefIndex;
1702         aNewEndFeature =
1703             aRefIndex >= aRefs->Lower() ? feature(aRefs->Value(aRefIndex)) : FeaturePtr();
1704       } while (aNewEndFeature && isSkippedFeature(aNewEndFeature));
1705       aFolderEndFeature = aNewEndFeature;
1706     }
1707   }
1708
1709   // update folder references
1710   aFoundFolder->reference(ModelAPI_Folder::FIRST_FEATURE_ID())->setValue(aFolderStartFeature);
1711   aFoundFolder->reference(ModelAPI_Folder::LAST_FEATURE_ID())->setValue(aFolderEndFeature);
1712
1713   updateHistory(ModelAPI_Feature::group());
1714   return true;
1715 }
1716
1717 FolderPtr Model_Objects::findContainingFolder(const FeaturePtr& theFeature, int& theIndexInFolder)
1718 {
1719   // search the label in the list of references
1720   TDF_Label aFeaturesLab = featuresLabel();
1721   Handle(TDataStd_ReferenceArray) aRefs;
1722   if (!aFeaturesLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
1723     return FolderPtr(); // no reference array (something is wrong)
1724
1725   std::shared_ptr<Model_Data> aData =
1726       std::static_pointer_cast<Model_Data>(theFeature->data());
1727   if (!aData || !aData->isValid())
1728     return FolderPtr();
1729   TDF_Label aLabelToFind = aData->label().Father();
1730
1731   theIndexInFolder = -1;
1732   FolderPtr aFoundFolder;
1733   TDF_Label aLastFeatureLabel;
1734
1735   for (int aRefIndex = aRefs->Lower(); aRefIndex <= aRefs->Upper(); ++aRefIndex) {
1736     TDF_Label aCurLabel = aRefs->Value(aRefIndex);
1737
1738     if (aFoundFolder)
1739       ++theIndexInFolder;
1740
1741     if (aCurLabel == aLabelToFind) { // the feature is reached
1742       if (aFoundFolder) {
1743         if (isSkippedFeature(theFeature)) {
1744           theIndexInFolder = -1;
1745           return FolderPtr();
1746         }
1747         // decrease the index of the feature in the folder by the number of skipped features
1748         for (int anIndex = theIndexInFolder - 1; anIndex > 0; anIndex--) {
1749           aCurLabel = aRefs->Value(aRefIndex - anIndex);
1750           if (isSkippedFeature(feature(aCurLabel)))
1751             theIndexInFolder--;
1752         }
1753       }
1754       return aFoundFolder;
1755     }
1756
1757     if (!aFoundFolder) {
1758       // if the current label refers to a folder, feel all necessary data
1759       const ObjectPtr& aFolderObj = folder(aCurLabel);
1760       if (aFolderObj.get()) {
1761         aFoundFolder = std::dynamic_pointer_cast<ModelAPI_Folder>(aFolderObj);
1762         theIndexInFolder = -1;
1763
1764         AttributeReferencePtr aLastRef =
1765             aFoundFolder->reference(ModelAPI_Folder::LAST_FEATURE_ID());
1766         if (aLastRef->value()) {
1767           aData = std::static_pointer_cast<Model_Data>(aLastRef->value()->data());
1768           if (aData && aData->isValid())
1769             aLastFeatureLabel = aData->label().Father();
1770         } else // folder is empty
1771           aFoundFolder = FolderPtr();
1772       }
1773     } else if (aLastFeatureLabel == aCurLabel) {
1774       // folder is finished, clear all stored data
1775       theIndexInFolder = -1;
1776       aFoundFolder = FolderPtr();
1777     }
1778   }
1779
1780   // folder is not found
1781   theIndexInFolder = -1;
1782   return FolderPtr();
1783 }
1784
1785
1786 std::shared_ptr<ModelAPI_Feature> Model_Objects::feature(
1787     const std::shared_ptr<ModelAPI_Result>& theResult)
1788 {
1789   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(theResult->data());
1790   if (aData.get()) {
1791     TDF_Label aFeatureLab = aData->label().Father().Father().Father();
1792     FeaturePtr aFeature = feature(aFeatureLab);
1793     while(!aFeature.get() && aFeatureLab.Depth() > 1) { // this may be sub-result of result
1794       aFeatureLab = aFeatureLab.Father().Father();
1795       aFeature = feature(aFeatureLab);
1796     }
1797     return aFeature;
1798   }
1799   return FeaturePtr();
1800 }
1801
1802 std::string Model_Objects::featureResultGroup(FeaturePtr theFeature)
1803 {
1804   if (theFeature->data()->isValid()) {
1805     TDF_ChildIterator aLabIter(resultLabel(theFeature->data(), 0).Father());
1806     if (aLabIter.More()) {
1807       TDF_Label anArgLab = aLabIter.Value();
1808       Handle(TDataStd_Comment) aGroup;
1809       if (aLabIter.Value().FindAttribute(TDataStd_Comment::GetID(), aGroup)) {
1810         return TCollection_AsciiString(aGroup->Get()).ToCString();
1811       }
1812     }
1813   }
1814   static std::string anEmpty;
1815   return anEmpty; // not found
1816 }
1817
1818 void Model_Objects::updateResults(FeaturePtr theFeature, std::set<FeaturePtr>& theProcessed)
1819 {
1820   if (theProcessed.find(theFeature) != theProcessed.end())
1821     return;
1822   theProcessed.insert(theFeature);
1823   // for composites update subs recursively (sketch elements results are needed for the sketch)
1824   CompositeFeaturePtr aComp = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theFeature);
1825   if (aComp.get() && aComp->getKind() != "Part") { // don't go inside of parts sub-features
1826     // update subs of composites first
1827     int aSubNum = aComp->numberOfSubs();
1828     for(int a = 0; a < aSubNum; a++) {
1829       FeaturePtr aSub = aComp->subFeature(a);
1830       updateResults(aComp->subFeature(a), theProcessed);
1831     }
1832   }
1833
1834   // for not persistent is will be done by parametric updater automatically
1835   //if (!theFeature->isPersistentResult()) return;
1836   // check the existing results and remove them if there is nothing on the label
1837   std::list<ResultPtr>::const_iterator aResIter = theFeature->results().cbegin();
1838   while(aResIter != theFeature->results().cend()) {
1839     ResultPtr aBody = std::dynamic_pointer_cast<ModelAPI_Result>(*aResIter);
1840     if (aBody.get()) {
1841       std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(aBody->data());
1842       if (!aData.get() || !aData->isValid() || (!aBody->isDisabled() && aData->isDeleted())) {
1843         // found a disappeared result => remove it
1844         theFeature->eraseResultFromList(aBody);
1845         // start iterate from beginning because iterator is corrupted by removing
1846         aResIter = theFeature->results().cbegin();
1847         continue;
1848       }
1849     }
1850     aResIter++;
1851   }
1852   // it may be on undo
1853   if (!theFeature->data() || !theFeature->data()->isValid() || theFeature->isDisabled())
1854     return;
1855   // check that results are presented on all labels
1856   int aResSize = int(theFeature->results().size());
1857   TDF_ChildIterator aLabIter(resultLabel(theFeature->data(), 0).Father());
1858   for(; aLabIter.More(); aLabIter.Next()) {
1859     // here must be GUID of the feature
1860     int aResIndex = aLabIter.Value().Tag() - 1;
1861     ResultPtr aNewBody;
1862     if (aResSize <= aResIndex) {
1863       TDF_Label anArgLab = aLabIter.Value();
1864       Handle(TDataStd_Comment) aGroup;
1865       if (anArgLab.FindAttribute(TDataStd_Comment::GetID(), aGroup)) {
1866         if (aGroup->Get() == ModelAPI_ResultBody::group().c_str()) {
1867           aNewBody = createBody(theFeature->data(), aResIndex);
1868         } else if (aGroup->Get() == ModelAPI_ResultPart::group().c_str()) {
1869           std::shared_ptr<ModelAPI_ResultPart> aNewP = createPart(theFeature->data(), aResIndex);
1870           theFeature->setResult(aNewP, aResIndex);
1871           if (!aNewP->partDoc().get())
1872             // create the part result: it is better to restore the previous result if it is possible
1873             theFeature->execute();
1874         } else if (aGroup->Get() == ModelAPI_ResultConstruction::group().c_str()) {
1875           theFeature->execute(); // construction shapes are needed for sketch solver
1876         } else if (aGroup->Get() == ModelAPI_ResultGroup::group().c_str()) {
1877           aNewBody = createGroup(theFeature->data(), aResIndex);
1878         } else if (aGroup->Get() == ModelAPI_ResultField::group().c_str()) {
1879           aNewBody = createField(theFeature->data(), aResIndex);
1880         } else if (aGroup->Get() == ModelAPI_ResultParameter::group().c_str()) {
1881           theFeature->attributeChanged("expression"); // just produce a value
1882         } else {
1883           Events_InfoMessage("Model_Objects", "Unknown type of result is found in the document:")
1884             .arg(TCollection_AsciiString(aGroup->Get()).ToCString()).send();
1885         }
1886       }
1887       if (aNewBody && !aNewBody->data()->isDeleted()) {
1888         theFeature->setResult(aNewBody, aResIndex);
1889       }
1890     }
1891   }
1892 }
1893
1894 ResultPtr Model_Objects::findByName(const std::string theName)
1895 {
1896   ResultPtr aResult;
1897   FeaturePtr aResFeature; // keep feature to return the latest one
1898   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator anObjIter(myFeatures);
1899   for(; anObjIter.More(); anObjIter.Next()) {
1900     FeaturePtr& aFeature = anObjIter.ChangeValue();
1901     if (!aFeature.get() || aFeature->isDisabled()) // may be on close
1902       continue;
1903     std::list<ResultPtr> allResults;
1904     ModelAPI_Tools::allResults(aFeature, allResults);
1905     std::list<ResultPtr>::iterator aRIter = allResults.begin();
1906     for (; aRIter != allResults.cend(); aRIter++) {
1907       ResultPtr aRes = *aRIter;
1908       if (aRes.get() && aRes->data() && aRes->data()->isValid() && !aRes->isDisabled() &&
1909           aRes->data()->name() == theName)
1910       {
1911         if (!aResult.get() || isLater(aFeature, aResFeature)) { // select the latest
1912           aResult = aRes;
1913           aResFeature = aFeature;
1914         }
1915       }
1916     }
1917   }
1918   return aResult;
1919 }
1920
1921 TDF_Label Model_Objects::nextLabel(TDF_Label theCurrent, const bool theReverse)
1922 {
1923   Handle(TDataStd_ReferenceArray) aRefs;
1924   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
1925     for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) { // iterate all existing features
1926       TDF_Label aCurLab = aRefs->Value(a);
1927       if (aCurLab.IsEqual(theCurrent)) {
1928         a += theReverse ? -1 : 1;
1929         if (a >= aRefs->Lower() && a <= aRefs->Upper())
1930           return aRefs->Value(a);
1931         break; // finish iiteration: it's last feature
1932       }
1933     }
1934   }
1935   return TDF_Label();
1936 }
1937
1938 FeaturePtr Model_Objects::nextFeature(FeaturePtr theCurrent, const bool theReverse)
1939 {
1940   std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theCurrent->data());
1941   if (aData.get() && aData->isValid()) {
1942     TDF_Label aFeatureLabel = aData->label().Father();
1943     do {
1944       TDF_Label aNextLabel = nextLabel(aFeatureLabel, theReverse);
1945       if (aNextLabel.IsNull())
1946         break; // last or something is wrong
1947       FeaturePtr aFound = feature(aNextLabel);
1948       if (aFound)
1949         return aFound; // the feature is found
1950       // if the next label is a folder, skip it
1951       aFeatureLabel = folder(aNextLabel).get() ? aNextLabel : TDF_Label();
1952     } while (!aFeatureLabel.IsNull());
1953   }
1954   return FeaturePtr(); // not found, last, or something is wrong
1955 }
1956
1957 FeaturePtr Model_Objects::firstFeature()
1958 {
1959   Handle(TDataStd_ReferenceArray) aRefs;
1960   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
1961     return feature(aRefs->Value(aRefs->Lower()));
1962   }
1963   return FeaturePtr(); // no features at all
1964 }
1965
1966 FeaturePtr Model_Objects::lastFeature()
1967 {
1968   Handle(TDataStd_ReferenceArray) aRefs;
1969   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
1970     FeaturePtr aLast = feature(aRefs->Value(aRefs->Upper()));
1971     if (!aLast.get() && aRefs->Length() != 0) { // erase the invalid feature from the array
1972       RemoveFromRefArray(featuresLabel(), aRefs->Value(aRefs->Upper()));
1973       return lastFeature(); // try once again, after the last was removed
1974     }
1975     return feature(aRefs->Value(aRefs->Upper()));
1976   }
1977   return FeaturePtr(); // no features at all
1978 }
1979
1980 bool Model_Objects::isLater(FeaturePtr theLater, FeaturePtr theCurrent) const
1981 {
1982   std::shared_ptr<Model_Data> aLaterD = std::static_pointer_cast<Model_Data>(theLater->data());
1983   std::shared_ptr<Model_Data> aCurrentD = std::static_pointer_cast<Model_Data>(theCurrent->data());
1984   if (aLaterD.get() && aLaterD->isValid() && aCurrentD.get() && aCurrentD->isValid()) {
1985     TDF_Label aLaterL = aLaterD->label().Father();
1986     TDF_Label aCurrentL = aCurrentD->label().Father();
1987     int aLaterI = -1, aCurentI = -1; // not found yet state
1988     Handle(TDataStd_ReferenceArray) aRefs;
1989     if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
1990       for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) { // iterate all existing features
1991         TDF_Label aCurLab = aRefs->Value(a);
1992         if (aCurLab.IsEqual(aLaterL)) {
1993           aLaterI = a;
1994         } else if (aCurLab.IsEqual(aCurrentL)) {
1995           aCurentI = a;
1996         } else continue;
1997         if (aLaterI != -1 && aCurentI != -1) // both are found
1998           return aLaterI > aCurentI;
1999       }
2000     }
2001   }
2002   return false; // not found, or something is wrong
2003 }
2004
2005 std::list<std::shared_ptr<ModelAPI_Object> > Model_Objects::allObjects()
2006 {
2007   std::list<std::shared_ptr<ModelAPI_Object> > aResult;
2008   Handle(TDataStd_ReferenceArray) aRefs;
2009   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
2010     for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
2011       ObjectPtr anObject = object(aRefs->Value(a));
2012       if (!anObject.get()) // is it a folder?
2013         anObject = folder(aRefs->Value(a));
2014       if (anObject.get())
2015         aResult.push_back(anObject);
2016     }
2017   }
2018   return aResult;
2019 }
2020
2021 std::list<std::shared_ptr<ModelAPI_Feature> > Model_Objects::allFeatures()
2022 {
2023   std::list<std::shared_ptr<ModelAPI_Feature> > aResult;
2024   Handle(TDataStd_ReferenceArray) aRefs;
2025   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
2026     for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
2027       FeaturePtr aFeature = feature(aRefs->Value(a));
2028       if (aFeature.get())
2029         aResult.push_back(aFeature);
2030     }
2031   }
2032   return aResult;
2033 }
2034
2035 int Model_Objects::numInternalFeatures()
2036 {
2037   Handle(TDataStd_ReferenceArray) aRefs;
2038   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
2039     return aRefs->Upper() - aRefs->Lower() + 1;
2040   }
2041   return 0; // invalid
2042 }
2043
2044 std::shared_ptr<ModelAPI_Feature> Model_Objects::internalFeature(const int theIndex)
2045 {
2046   Handle(TDataStd_ReferenceArray) aRefs;
2047   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
2048     return feature(aRefs->Value(aRefs->Lower() + theIndex));
2049   }
2050   return FeaturePtr(); // invalid
2051 }
2052
2053 Standard_Integer HashCode(const TDF_Label& theLab, const Standard_Integer theUpper)
2054 {
2055   return TDF_LabelMapHasher::HashCode(theLab, theUpper);
2056
2057 }
2058 Standard_Boolean IsEqual(const TDF_Label& theLab1, const TDF_Label& theLab2)
2059 {
2060   return TDF_LabelMapHasher::IsEqual(theLab1, theLab2);
2061 }