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