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