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