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