Salome HOME
Support of wide string
[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::wstring& 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::wstring composeName(const std::string& theFeatureKind, const int theIndex)
734 {
735   std::stringstream aNameStream;
736   aNameStream << theFeatureKind << "_" << theIndex;
737   return ModelAPI_Tools::toWString(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::wstring 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::wstring> 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::wstring 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             // if feature contains results, re-init them too
890             if (aFeature.get()) {
891               std::list<ResultPtr> aResults;
892               ModelAPI_Tools::allResults(aFeature, aResults);
893               std::list<ResultPtr>::iterator aResIter = aResults.begin();
894               for(; aResIter != aResults.end(); aResIter++) {
895                 std::list<std::shared_ptr<ModelAPI_Attribute> > anAttrs =
896                   (*aResIter)->data()->attributes("");
897                 std::list<std::shared_ptr<ModelAPI_Attribute> >::iterator anAttr = anAttrs.begin();
898                 for(; anAttr != anAttrs.end(); anAttr++)
899                   (*anAttr)->reinit();
900               }
901             }
902           }
903         }
904         ModelAPI_EventCreator::get()->sendUpdated(anObject, anUpdateEvent);
905         if (aFeature && aFeature->getKind() == "Parameter") {
906           // if parameters are changed, update the results (issue 937)
907           const std::list<std::shared_ptr<ModelAPI_Result> >& aResults = aFeature->results();
908           std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aRIter = aResults.begin();
909           for (; aRIter != aResults.cend(); aRIter++) {
910             std::shared_ptr<ModelAPI_Result> aRes = *aRIter;
911             if (aRes->data()->isValid() && !aRes->isDisabled()) {
912               ModelAPI_EventCreator::get()->sendUpdated(aRes, anUpdateEvent);
913             }
914           }
915         }
916       }
917     }
918   }
919
920   // check all features are checked: if not => it was removed
921   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFIter(myFeatures);
922   while (aFIter.More()) {
923     if (aKeptFeatures.find(aFIter.Value()) == aKeptFeatures.end()
924       && aNewFeatures.find(aFIter.Value()) == aNewFeatures.end()) {
925         FeaturePtr aFeature = aFIter.Value();
926         // event: model is updated
927         //if (aFeature->isInHistory()) {
928         ModelAPI_EventCreator::get()->sendDeleted(myDoc, ModelAPI_Feature::group());
929         //}
930         // results of this feature must be redisplayed (hided)
931         // redisplay also removed feature (used for sketch and AISObject)
932         ModelAPI_EventCreator::get()->sendUpdated(aFeature, aRedispEvent);
933         updateHistory(aFeature);
934         aFeature->erase();
935
936         // unbind after the "erase" call: on abort sketch
937         // is removes sub-objects that corrupts aFIter
938         myFeatures.UnBind(aFIter.Key());
939         // reinitialize iterator because unbind may corrupt the previous order in the map
940         aFIter.Initialize(myFeatures);
941     } else
942       aFIter.Next();
943   }
944   // verify folders are checked: if not => is was removed
945   for (NCollection_DataMap<TDF_Label, ObjectPtr>::Iterator aFldIt(myFolders);
946        aFldIt.More(); aFldIt.Next()) {
947     ObjectPtr aCurObj = aFldIt.Value();
948     if (aKeptFeatures.find(aCurObj) == aKeptFeatures.end() &&
949         aNewFeatures.find(aCurObj) == aNewFeatures.end()) {
950       ModelAPI_EventCreator::get()->sendDeleted(myDoc, ModelAPI_Folder::group());
951       // results of this feature must be redisplayed (hided)
952       // redisplay also removed feature (used for sketch and AISObject)
953       ModelAPI_EventCreator::get()->sendUpdated(aCurObj, aRedispEvent);
954       updateHistory(aCurObj);
955       aCurObj->erase();
956
957       // unbind after the "erase" call: on abort sketch
958       // is removes sub-objects that corrupts aFIter
959       myFolders.UnBind(aFldIt.Key());
960       // reinitialize iterator because unbind may corrupt the previous order in the map
961       aFldIt.Initialize(myFolders);
962     }
963   }
964
965   if (theUpdateReferences) {
966     synchronizeBackRefs();
967   }
968   // update results of the features (after features created because
969   // they may be connected, like sketch and sub elements)
970   // After synchronization of back references because sketch
971   // must be set in sub-elements before "execute" by updateResults
972   std::set<FeaturePtr> aProcessed; // composites must be updated after their subs (issue 360)
973   TDF_ChildIDIterator aLabIter2(featuresLabel(), TDataStd_Comment::GetID());
974   for (; aLabIter2.More(); aLabIter2.Next()) {
975     TDF_Label aFeatureLabel = aLabIter2.Value()->Label();
976     if (myFeatures.IsBound(aFeatureLabel)) {  // a new feature is inserted
977       FeaturePtr aFeature = myFeatures.Find(aFeatureLabel);
978       updateResults(aFeature, aProcessed);
979     }
980   }
981   // the synchronize should be done after updateResults
982   // in order to correct back references of updated results
983   if (theUpdateReferences) {
984     synchronizeBackRefs();
985   }
986   if (!theUpdated.IsEmpty()) {
987     // this means there is no control what was modified => remove history cash
988     myHistory.clear();
989   }
990
991   if (!theExecuteFeatures)
992     anOwner->setExecuteFeatures(false);
993   aLoop->activateFlushes(isActive);
994
995   if (theFlush) {
996     aLoop->flush(aDeleteEvent);
997     // delete should be emitted before create to reacts to aborted feature
998     aLoop->flush(aCreateEvent);
999     aLoop->flush(anUpdateEvent);
1000     aLoop->flush(aCreateEvent); // after update of features, there could be results created
1001     aLoop->flush(aDeleteEvent); // or deleted
1002     aLoop->flush(aRedispEvent);
1003     aLoop->flush(aToHideEvent);
1004   }
1005   if (!theExecuteFeatures)
1006     anOwner->setExecuteFeatures(true);
1007 }
1008
1009 /// synchronizes back references for the given object basing on the collected data
1010 void Model_Objects::synchronizeBackRefsForObject(const std::set<AttributePtr>& theNewRefs,
1011   ObjectPtr theObject)
1012 {
1013   if (!theObject.get() || !theObject->data()->isValid())
1014     return; // invalid
1015   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(theObject->data());
1016   // iterate new list to compare with current
1017   std::set<AttributePtr>::iterator aNewIter = theNewRefs.begin();
1018   for(; aNewIter != theNewRefs.end(); aNewIter++) {
1019     // for the Model_AttributeRefList erase cash (issue #2819)
1020     std::shared_ptr<Model_AttributeRefList> aRefList =
1021       std::dynamic_pointer_cast<Model_AttributeRefList>(*aNewIter);
1022     if (aRefList)
1023       aRefList->eraseHash();
1024
1025     if (aData->refsToMe().find(*aNewIter) == aData->refsToMe().end()) {
1026       FeaturePtr aRefFeat = std::dynamic_pointer_cast<ModelAPI_Feature>((*aNewIter)->owner());
1027       if (aRefFeat)
1028         aData->addBackReference(aRefFeat, (*aNewIter)->id());
1029       else // add back reference to a folder
1030         aData->addBackReference((*aNewIter)->owner(), (*aNewIter)->id());
1031     }
1032   }
1033   if (theNewRefs.size() != aData->refsToMe().size()) { // some back ref must be removed
1034     std::set<AttributePtr>::iterator aCurrentIter = aData->refsToMe().begin();
1035     while(aCurrentIter != aData->refsToMe().end()) {
1036       if (theNewRefs.find(*aCurrentIter) == theNewRefs.end()) {
1037         // for external references from other documents this system
1038         // is not working: refs are collected from
1039         // different Model_Objects, so before remove check this
1040         // external object exists and still referenced
1041         bool aLeaveIt = false;
1042         if ((*aCurrentIter)->owner().get() && (*aCurrentIter)->owner()->document() != myDoc &&
1043             (*aCurrentIter)->owner()->data().get() && (*aCurrentIter)->owner()->data()->isValid()) {
1044           std::list<std::pair<std::string, std::list<std::shared_ptr<ModelAPI_Object> > > > aRefs;
1045           (*aCurrentIter)->owner()->data()->referencesToObjects(aRefs);
1046           std::list<std::pair<std::string, std::list<std::shared_ptr<ModelAPI_Object> >>>::iterator
1047             aRefIter = aRefs.begin();
1048           for(; aRefIter != aRefs.end(); aRefIter++) {
1049             if ((*aCurrentIter)->id() == aRefIter->first) {
1050               std::list<std::shared_ptr<ModelAPI_Object> >::iterator anOIt;
1051               for(anOIt = aRefIter->second.begin(); anOIt != aRefIter->second.end(); anOIt++) {
1052                 if (*anOIt == theObject) {
1053                   aLeaveIt = true;
1054                 }
1055               }
1056             }
1057           }
1058         }
1059         if (!aLeaveIt) {
1060           aData->removeBackReference(*aCurrentIter);
1061           aCurrentIter = aData->refsToMe().begin(); // reinitialize iteration after delete
1062         } else aCurrentIter++;
1063       } else aCurrentIter++;
1064     }
1065   }
1066   // for the last feature in the folder, check if it is a sub-feature,
1067   // then refer the folder to a top-level parent composite feature
1068   const std::set<AttributePtr>& aRefs = aData->refsToMe();
1069   std::set<AttributePtr>::iterator anIt = aRefs.begin();
1070   for (; anIt != aRefs.end(); ++anIt)
1071     if ((*anIt)->id() == ModelAPI_Folder::LAST_FEATURE_ID())
1072       break;
1073   if (anIt != aRefs.end()) {
1074     FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
1075     if (aFeature) {
1076       CompositeFeaturePtr aParent;
1077       CompositeFeaturePtr aGrandParent = ModelAPI_Tools::compositeOwner(aFeature);
1078       do {
1079         aParent = aGrandParent;
1080         if (aGrandParent)
1081           aGrandParent = ModelAPI_Tools::compositeOwner(aParent);
1082       } while (aGrandParent.get());
1083       if (aParent) {
1084         ObjectPtr aFolder = (*anIt)->owner();
1085         // remove reference from the current feature
1086         aData->removeBackReference(aFolder, ModelAPI_Folder::LAST_FEATURE_ID());
1087         // set reference to a top-level parent
1088         aFolder->data()->reference(ModelAPI_Folder::LAST_FEATURE_ID())->setValue(aParent);
1089         std::shared_ptr<Model_Data> aParentData =
1090             std::dynamic_pointer_cast<Model_Data>(aParent->data());
1091         aParentData->addBackReference(aFolder, ModelAPI_Folder::LAST_FEATURE_ID());
1092       }
1093     }
1094   }
1095   aData->updateConcealmentFlag();
1096 }
1097
1098 static void collectReferences(std::shared_ptr<ModelAPI_Data> theData,
1099                               std::map<ObjectPtr, std::set<AttributePtr> >& theRefs)
1100 {
1101   if (theData.get()) {
1102     std::list<std::pair<std::string, std::list<ObjectPtr> > > aRefs;
1103     theData->referencesToObjects(aRefs);
1104     std::list<std::pair<std::string, std::list<ObjectPtr> > >::iterator aRefsIt = aRefs.begin();
1105     for(; aRefsIt != aRefs.end(); aRefsIt++) {
1106       std::list<ObjectPtr>::iterator aRefTo = aRefsIt->second.begin();
1107       for(; aRefTo != aRefsIt->second.end(); aRefTo++) {
1108         if (*aRefTo) {
1109           std::map<ObjectPtr, std::set<AttributePtr> >::iterator aFound = theRefs.find(*aRefTo);
1110           if (aFound == theRefs.end()) {
1111             theRefs[*aRefTo] = std::set<AttributePtr>();
1112             aFound = theRefs.find(*aRefTo);
1113           }
1114           aFound->second.insert(theData->attribute(aRefsIt->first));
1115         }
1116       }
1117     }
1118   }
1119 }
1120
1121 void Model_Objects::synchronizeBackRefs()
1122 {
1123   // collect all back references in the separated container: to update everything at once,
1124   // without additional Concealment switching on and off: only the final modification
1125
1126   // referenced (slave) objects to referencing attributes
1127   std::map<ObjectPtr, std::set<AttributePtr> > allRefs;
1128   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator aFeatures(myFeatures);
1129   for(; aFeatures.More(); aFeatures.Next()) {
1130     FeaturePtr aFeature = aFeatures.Value();
1131     collectReferences(aFeature->data(), allRefs);
1132   }
1133   NCollection_DataMap<TDF_Label, ObjectPtr>::Iterator aFolders(myFolders);
1134   for(; aFolders.More(); aFolders.Next()) {
1135     ObjectPtr aFolder = aFolders.Value();
1136     collectReferences(aFolder->data(), allRefs);
1137   }
1138   // second iteration: just compare back-references with existing in features and results
1139   for(aFeatures.Initialize(myFeatures); aFeatures.More(); aFeatures.Next()) {
1140     FeaturePtr aFeature = aFeatures.Value();
1141     static std::set<AttributePtr> anEmpty;
1142     std::map<ObjectPtr, std::set<AttributePtr> >::iterator aFound = allRefs.find(aFeature);
1143     if (aFound == allRefs.end()) { // not found => erase all back references
1144       synchronizeBackRefsForObject(anEmpty, aFeature);
1145     } else {
1146       synchronizeBackRefsForObject(aFound->second, aFeature);
1147       allRefs.erase(aFound); // to check that all refs are counted
1148     }
1149     // also for results
1150     std::list<ResultPtr> aResults;
1151     ModelAPI_Tools::allResults(aFeature, aResults);
1152     std::list<ResultPtr>::iterator aRIter = aResults.begin();
1153     for(; aRIter != aResults.cend(); aRIter++) {
1154       aFound = allRefs.find(*aRIter);
1155       if (aFound == allRefs.end()) { // not found => erase all back references
1156         synchronizeBackRefsForObject(anEmpty, *aRIter);
1157       } else {
1158         synchronizeBackRefsForObject(aFound->second, *aRIter);
1159         allRefs.erase(aFound); // to check that all refs are counted
1160       }
1161     }
1162   }
1163   for(aFeatures.Initialize(myFeatures); aFeatures.More(); aFeatures.Next()) {
1164     FeaturePtr aFeature = aFeatures.Value();
1165     std::list<ResultPtr> aResults;
1166     ModelAPI_Tools::allResults(aFeature, aResults);
1167     // update the concealment status for display in isConcealed of ResultBody
1168     std::list<ResultPtr>::iterator aRIter = aResults.begin();
1169     for(; aRIter != aResults.cend(); aRIter++) {
1170       (*aRIter)->isConcealed();
1171     }
1172   }
1173   // the rest all refs means that feature references to the external document feature:
1174   // process also them
1175   std::map<ObjectPtr, std::set<AttributePtr> >::iterator anExtIter = allRefs.begin();
1176   for(; anExtIter != allRefs.end(); anExtIter++) {
1177     synchronizeBackRefsForObject(anExtIter->second, anExtIter->first);
1178   }
1179 }
1180
1181 TDF_Label Model_Objects::resultLabel(
1182   const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theResultIndex)
1183 {
1184   const std::shared_ptr<Model_Data>& aData =
1185     std::dynamic_pointer_cast<Model_Data>(theFeatureData);
1186   return aData->label().Father().FindChild(TAG_FEATURE_RESULTS).FindChild(theResultIndex + 1);
1187 }
1188
1189 bool Model_Objects::hasCustomName(DataPtr theFeatureData,
1190                                   ResultPtr theResult,
1191                                   int theResultIndex,
1192                                   std::wstring& theParentName) const
1193 {
1194   ResultBodyPtr aBodyRes = std::dynamic_pointer_cast<ModelAPI_ResultBody>(theFeatureData->owner());
1195   if (aBodyRes) {
1196     // only for top-results (works for the cases when results are not yet added to the feature)
1197     FeaturePtr anOwner = ModelAPI_Feature::feature(theResult);
1198
1199     // names of sub-solids in CompSolid should be default (for example,
1200     // result of boolean operation 'Boolean_1' is a CompSolid which is renamed to 'MyBOOL',
1201     // however, sub-elements of 'MyBOOL' should be named 'Boolean_1_1', 'Boolean_1_2' etc.)
1202     if (std::dynamic_pointer_cast<Model_Data>(aBodyRes->data())->label().Depth() == 6) {
1203       std::wostringstream aDefaultName;
1204       // compute default name of CompSolid (name of feature + index of CompSolid's result)
1205       int aBodyResultIndex = 0;
1206       const std::list<ResultPtr>& aResults = anOwner->results();
1207       std::list<ResultPtr>::const_iterator anIt = aResults.begin();
1208       for (; anIt != aResults.end(); ++anIt, ++aBodyResultIndex)
1209         if (aBodyRes == *anIt)
1210           break;
1211       aDefaultName << anOwner->name();
1212       aDefaultName << "_" << (aBodyResultIndex + 1);
1213       theParentName = aDefaultName.str();
1214     } else { // just name of the parent result if it is deeper than just a sub-result
1215       theParentName = aBodyRes->data()->name();
1216     }
1217     return false;
1218   }
1219
1220   std::pair<std::wstring, bool> aName = ModelAPI_Tools::getDefaultName(theResult);
1221   if (aName.second)
1222     theParentName = aName.first;
1223   return aName.second;
1224 }
1225
1226 void Model_Objects::storeResult(std::shared_ptr<ModelAPI_Data> theFeatureData,
1227                                 std::shared_ptr<ModelAPI_Result> theResult,
1228                                 const int theResultIndex)
1229 {
1230   theResult->init();
1231   theResult->setDoc(myDoc);
1232   initData(theResult, resultLabel(theFeatureData, theResultIndex), TAG_FEATURE_ARGUMENTS);
1233   if (theResult->data()->name().empty()) {
1234     // if was not initialized, generate event and set a name
1235     std::wstring aNewName = theFeatureData->name();
1236     if (hasCustomName(theFeatureData, theResult, theResultIndex, aNewName)) {
1237       // if the name of result is user-defined, then, at first time, assign name of the result
1238       // by empty string to be sure that corresponding flag in the data model is set
1239       theResult->data()->setName(L"");
1240     } else {
1241       std::wstringstream aName;
1242       aName << aNewName;
1243       // if there are several results (issue #899: any number of result),
1244       // add unique prefix starting from second
1245       if (theResultIndex > 0 || theResult->groupName() == ModelAPI_ResultBody::group())
1246         aName << "_" << theResultIndex + 1;
1247       aNewName = aName.str();
1248     }
1249     theResult->data()->setName(aNewName);
1250   }
1251 }
1252
1253 std::shared_ptr<ModelAPI_ResultConstruction> Model_Objects::createConstruction(
1254     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1255 {
1256   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1257   TDataStd_Comment::Set(aLab, ModelAPI_ResultConstruction::group().c_str());
1258   ObjectPtr anOldObject = object(aLab);
1259   std::shared_ptr<ModelAPI_ResultConstruction> aResult;
1260   if (anOldObject.get()) {
1261     aResult = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(anOldObject);
1262   }
1263   if (!aResult.get()) {
1264     aResult = std::shared_ptr<ModelAPI_ResultConstruction>(new Model_ResultConstruction);
1265     storeResult(theFeatureData, aResult, theIndex);
1266   }
1267   return aResult;
1268 }
1269
1270 std::shared_ptr<ModelAPI_ResultBody> Model_Objects::createBody(
1271     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1272 {
1273   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1274   TDataStd_Comment::Set(aLab, ModelAPI_ResultBody::group().c_str());
1275   ObjectPtr anOldObject = object(aLab);
1276   std::shared_ptr<ModelAPI_ResultBody> aResult;
1277   if (anOldObject.get()) {
1278     aResult = std::dynamic_pointer_cast<ModelAPI_ResultBody>(anOldObject);
1279   }
1280   if (!aResult.get()) {
1281     aResult = std::shared_ptr<ModelAPI_ResultBody>(new Model_ResultBody);
1282     storeResult(theFeatureData, aResult, theIndex);
1283   }
1284   return aResult;
1285 }
1286
1287 std::shared_ptr<ModelAPI_ResultPart> Model_Objects::createPart(
1288     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1289 {
1290   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1291   TDataStd_Comment::Set(aLab, ModelAPI_ResultPart::group().c_str());
1292   ObjectPtr anOldObject = object(aLab);
1293   std::shared_ptr<ModelAPI_ResultPart> aResult;
1294   if (anOldObject.get()) {
1295     aResult = std::dynamic_pointer_cast<ModelAPI_ResultPart>(anOldObject);
1296   }
1297   if (!aResult.get()) {
1298     aResult = std::shared_ptr<ModelAPI_ResultPart>(new Model_ResultPart);
1299     storeResult(theFeatureData, aResult, theIndex);
1300   }
1301   return aResult;
1302 }
1303
1304 std::shared_ptr<ModelAPI_ResultPart> Model_Objects::copyPart(
1305     const std::shared_ptr<ModelAPI_ResultPart>& theOrigin,
1306     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1307 {
1308   std::shared_ptr<ModelAPI_ResultPart> aResult = createPart(theFeatureData, theIndex);
1309   aResult->data()->reference(Model_ResultPart::BASE_REF_ID())->setValue(theOrigin);
1310   return aResult;
1311 }
1312
1313 std::shared_ptr<ModelAPI_ResultGroup> Model_Objects::createGroup(
1314     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1315 {
1316   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1317   TDataStd_Comment::Set(aLab, ModelAPI_ResultGroup::group().c_str());
1318   ObjectPtr anOldObject = object(aLab);
1319   std::shared_ptr<ModelAPI_ResultGroup> aResult;
1320   if (anOldObject.get()) {
1321     aResult = std::dynamic_pointer_cast<ModelAPI_ResultGroup>(anOldObject);
1322   }
1323   if (!aResult.get()) {
1324     aResult = std::shared_ptr<ModelAPI_ResultGroup>(new Model_ResultGroup(theFeatureData));
1325     storeResult(theFeatureData, aResult, theIndex);
1326   }
1327   return aResult;
1328 }
1329
1330 std::shared_ptr<ModelAPI_ResultField> Model_Objects::createField(
1331     const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1332 {
1333   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1334   TDataStd_Comment::Set(aLab, ModelAPI_ResultField::group().c_str());
1335   ObjectPtr anOldObject = object(aLab);
1336   std::shared_ptr<ModelAPI_ResultField> aResult;
1337   if (anOldObject.get()) {
1338     aResult = std::dynamic_pointer_cast<ModelAPI_ResultField>(anOldObject);
1339   }
1340   if (!aResult.get()) {
1341     aResult = std::shared_ptr<ModelAPI_ResultField>(new Model_ResultField(theFeatureData));
1342     storeResult(theFeatureData, aResult, theIndex);
1343   }
1344   return aResult;
1345 }
1346
1347 std::shared_ptr<ModelAPI_ResultParameter> Model_Objects::createParameter(
1348       const std::shared_ptr<ModelAPI_Data>& theFeatureData, const int theIndex)
1349 {
1350   TDF_Label aLab = resultLabel(theFeatureData, theIndex);
1351   TDataStd_Comment::Set(aLab, ModelAPI_ResultParameter::group().c_str());
1352   ObjectPtr anOldObject = object(aLab);
1353   std::shared_ptr<ModelAPI_ResultParameter> aResult;
1354   if (anOldObject.get()) {
1355     aResult = std::dynamic_pointer_cast<ModelAPI_ResultParameter>(anOldObject);
1356   }
1357   if (!aResult.get()) {
1358     aResult = std::shared_ptr<ModelAPI_ResultParameter>(new Model_ResultParameter);
1359     storeResult(theFeatureData, aResult, theIndex);
1360   }
1361   return aResult;
1362 }
1363
1364 std::shared_ptr<ModelAPI_Folder> Model_Objects::createFolder(
1365     const std::shared_ptr<ModelAPI_Feature>& theBeforeThis)
1366 {
1367   FolderPtr aFolder(new ModelAPI_Folder);
1368   if (!aFolder)
1369     return aFolder;
1370
1371   TDF_Label aFeaturesLab = featuresLabel();
1372   TDF_Label aFolderLab = aFeaturesLab.NewChild();
1373   // store feature in the features array: before "initData" because in macro features
1374   // in initData it creates new features, appeared later than this
1375   TDF_Label aPrevFeatureLab;
1376   if (theBeforeThis.get()) { // searching for the previous feature label
1377     std::shared_ptr<Model_Data> aPrevData =
1378         std::dynamic_pointer_cast<Model_Data>(theBeforeThis->data());
1379     if (aPrevData.get()) {
1380       int anIndex = kUNDEFINED_FEATURE_INDEX;
1381       aPrevFeatureLab = nextLabel(aPrevData->label().Father(), anIndex, true);
1382     }
1383   } else { // find the label of the last feature
1384     Handle(TDataStd_ReferenceArray) aRefs;
1385     if (aFeaturesLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
1386       aPrevFeatureLab = aRefs->Value(aRefs->Upper());
1387   }
1388   AddToRefArray(aFeaturesLab, aFolderLab, aPrevFeatureLab);
1389
1390   // keep the feature ID to restore document later correctly
1391   TDataStd_Comment::Set(aFolderLab, ModelAPI_Folder::ID().c_str());
1392   myFolders.Bind(aFolderLab, aFolder);
1393   // must be before the event sending: for OB the feature is already added
1394   updateHistory(ModelAPI_Folder::group());
1395   updateHistory(ModelAPI_Feature::group());
1396
1397   // must be after binding to the map because of "Box" macro feature that
1398   // creates other features in "initData"
1399   initData(aFolder, aFolderLab, TAG_FEATURE_ARGUMENTS);
1400   // event: folder is added, must be before "initData" to update OB correctly on Duplicate:
1401   // first new part, then the content
1402   static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_CREATED);
1403   ModelAPI_EventCreator::get()->sendUpdated(aFolder, anEvent);
1404
1405   return aFolder;
1406 }
1407
1408 void Model_Objects::removeFolder(std::shared_ptr<ModelAPI_Folder> theFolder)
1409 {
1410   std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theFolder->data());
1411   if (!aData.get() || !aData->isValid())
1412     return;
1413
1414   // this must be before erase since theFolder erasing removes all information about it
1415   clearHistory(theFolder);
1416   // erase fields
1417   theFolder->erase();
1418
1419   TDF_Label aFolderLabel = aData->label().Father();
1420   if (myFolders.IsBound(aFolderLabel))
1421     myFolders.UnBind(aFolderLabel);
1422
1423   static Events_ID EVENT_DISP = Events_Loop::loop()->eventByName(EVENT_OBJECT_TO_REDISPLAY);
1424   ModelAPI_EventCreator::get()->sendUpdated(theFolder, EVENT_DISP);
1425   // erase all attributes under the label of feature
1426   aFolderLabel.ForgetAllAttributes();
1427   // remove it from the references array
1428   RemoveFromRefArray(featuresLabel(), aFolderLabel);
1429   // event: feature is deleted
1430   ModelAPI_EventCreator::get()->sendDeleted(theFolder->document(), ModelAPI_Folder::group());
1431   updateHistory(ModelAPI_Folder::group());
1432   updateHistory(ModelAPI_Feature::group());
1433 }
1434
1435 // Returns one of the limiting features of the list
1436 static FeaturePtr limitingFeature(std::list<FeaturePtr>& theFeatures, const bool isLast)
1437 {
1438   FeaturePtr aFeature;
1439   if (isLast) {
1440     aFeature = theFeatures.back();
1441     theFeatures.pop_back();
1442   } else {
1443     aFeature = theFeatures.front();
1444     theFeatures.pop_front();
1445   }
1446   return aFeature;
1447 }
1448
1449 // Verify the feature is sub-element in composite feature or it is not used in the history
1450 static bool isSkippedFeature(FeaturePtr theFeature)
1451 {
1452   bool isSub = ModelAPI_Tools::compositeOwner(theFeature).get() != NULL;
1453   return isSub || (theFeature && !theFeature->isInHistory());
1454 }
1455
1456 std::shared_ptr<ModelAPI_Folder> Model_Objects::findFolder(
1457       const std::list<std::shared_ptr<ModelAPI_Feature> >& theFeatures,
1458       const bool theBelow)
1459 {
1460   if (theFeatures.empty())
1461     return FolderPtr(); // nothing to move
1462
1463   TDF_Label aFeaturesLab = featuresLabel();
1464   Handle(TDataStd_ReferenceArray) aRefs;
1465   if (!aFeaturesLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
1466     return FolderPtr(); // no reference array (something is wrong)
1467
1468   std::list<std::shared_ptr<ModelAPI_Feature> > aFeatures = theFeatures;
1469   std::shared_ptr<ModelAPI_Feature> aLimitingFeature = limitingFeature(aFeatures, theBelow);
1470
1471   std::shared_ptr<Model_Data> aData =
1472       std::static_pointer_cast<Model_Data>(aLimitingFeature->data());
1473   if (!aData || !aData->isValid())
1474     return FolderPtr(); // invalid feature
1475
1476   // label of the first feature in the list for fast searching
1477   TDF_Label aFirstFeatureLabel = aData->label().Father();
1478
1479   // find a folder above the features and
1480   // check the given features represent a sequential list of objects following the folder
1481   FolderPtr aFoundFolder;
1482   TDF_Label aLastFeatureInFolder;
1483   int aRefIndex = aRefs->Lower();
1484   for(; aRefIndex <= aRefs->Upper(); ++aRefIndex) { // iterate all existing features
1485     TDF_Label aCurLabel = aRefs->Value(aRefIndex);
1486     if (IsEqual(aCurLabel, aFirstFeatureLabel))
1487       break; // no need to continue searching
1488
1489     // searching the folder below, just continue to search last feature from the list
1490     if (theBelow)
1491       continue;
1492
1493     // issue #18733: check for the last feature in folder before checking the sub-feature,
1494     //               because the folder may end by the feature which is
1495     //               neither a sub-feature nor a feature in history.
1496     if (!aLastFeatureInFolder.IsNull()) {
1497       if (IsEqual(aCurLabel, aLastFeatureInFolder))
1498         aLastFeatureInFolder.Nullify(); // the last feature in the folder is achieved
1499       continue;
1500     }
1501
1502     // if feature is in sub-component, skip it
1503     FeaturePtr aCurFeature = feature(aCurLabel);
1504     if (isSkippedFeature(aCurFeature))
1505       continue;
1506
1507     const ObjectPtr& aFolderObj = folder(aCurLabel);
1508     if (aFolderObj.get()) {
1509       aFoundFolder = std::dynamic_pointer_cast<ModelAPI_Folder>(aFolderObj);
1510       AttributeReferencePtr aLastFeatAttr =
1511           aFoundFolder->reference(ModelAPI_Folder::LAST_FEATURE_ID());
1512       if (aLastFeatAttr) {
1513         // setup iterating inside a folder to find last feature
1514         ObjectPtr aLastFeature = aLastFeatAttr->value();
1515         if (aLastFeature) {
1516           aData = std::static_pointer_cast<Model_Data>(aLastFeature->data());
1517           if (aData && aData->isValid())
1518             aLastFeatureInFolder = aData->label().Father();
1519         }
1520       }
1521     }
1522   }
1523
1524   if (theBelow && aRefIndex < aRefs->Upper()) {
1525     TDF_Label aLabel;
1526     // skip following features which are sub-components or not in history
1527     for (int anIndex = aRefIndex + 1; anIndex <= aRefs->Upper(); ++anIndex) {
1528       aLabel = aRefs->Value(anIndex);
1529       FeaturePtr aCurFeature = feature(aLabel);
1530       if (!isSkippedFeature(aCurFeature))
1531         break;
1532     }
1533     // check the next object is a folder
1534     aFoundFolder = std::dynamic_pointer_cast<ModelAPI_Folder>(folder(aLabel));
1535   }
1536
1537   if (!aLastFeatureInFolder.IsNull() || // the last feature of the folder above is not found
1538       !aFoundFolder)
1539     return FolderPtr();
1540
1541   // check the given features are sequential list
1542   int aStep = theBelow ? -1 : 1;
1543   for (aRefIndex += aStep;
1544        !aFeatures.empty() && aRefIndex >= aRefs->Lower() && aRefIndex <= aRefs->Upper();
1545        aRefIndex += aStep) {
1546     TDF_Label aCurLabel = aRefs->Value(aRefIndex);
1547     // if feature is in sub-component, skip it
1548     FeaturePtr aCurFeature = feature(aCurLabel);
1549     if (isSkippedFeature(aCurFeature))
1550       continue;
1551
1552     aLimitingFeature = limitingFeature(aFeatures, theBelow);
1553     if (!aCurFeature->data()->isEqual(aLimitingFeature->data()))
1554       return FolderPtr(); // not a sequential list
1555   }
1556
1557   return aFoundFolder;
1558 }
1559
1560 bool Model_Objects::moveToFolder(
1561       const std::list<std::shared_ptr<ModelAPI_Feature> >& theFeatures,
1562       const std::shared_ptr<ModelAPI_Folder>& theFolder)
1563 {
1564   if (theFeatures.empty() || !theFolder)
1565     return false;
1566
1567   // labels for the folder and last feature in the list
1568   TDF_Label aFolderLabel, aLastFeatureLabel;
1569   std::shared_ptr<Model_Data> aData =
1570       std::static_pointer_cast<Model_Data>(theFolder->data());
1571   if (aData && aData->isValid())
1572     aFolderLabel = aData->label().Father();
1573   aData = std::static_pointer_cast<Model_Data>(theFeatures.back()->data());
1574   if (aData && aData->isValid())
1575     aLastFeatureLabel = aData->label().Father();
1576
1577   if (aFolderLabel.IsNull() || aLastFeatureLabel.IsNull())
1578     return false;
1579
1580   AttributeReferencePtr aFirstFeatAttr =
1581       theFolder->reference(ModelAPI_Folder::FIRST_FEATURE_ID());
1582   AttributeReferencePtr aLastFeatAttr =
1583       theFolder->reference(ModelAPI_Folder::LAST_FEATURE_ID());
1584   bool initFirstAttr = !aFirstFeatAttr->value().get();
1585   bool initLastAttr  = !aLastFeatAttr->value().get();
1586
1587   // check the folder is below the list of features
1588   bool isFolderBelow = false;
1589   TDF_Label aFeaturesLab = featuresLabel();
1590   Handle(TDataStd_ReferenceArray) aRefs;
1591   if (!aFeaturesLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
1592     return false; // no reference array (something is wrong)
1593   for (int aRefIndex = aRefs->Lower(); aRefIndex <= aRefs->Upper(); ++aRefIndex) {
1594     TDF_Label aCurLabel = aRefs->Value(aRefIndex);
1595     if (aCurLabel == aFolderLabel)
1596       break; // folder is above the features
1597     else if (aCurLabel == aLastFeatureLabel) {
1598       isFolderBelow = true;
1599       break;
1600     }
1601   }
1602
1603   if (isFolderBelow) {
1604     aData = std::static_pointer_cast<Model_Data>(theFeatures.front()->data());
1605     if (!aData || !aData->isValid())
1606       return false;
1607     TDF_Label aPrevFeatureLabel = aData->label().Father();
1608     // label of the feature before the first feature in the list
1609     for (int aRefIndex = aRefs->Lower(); aRefIndex <= aRefs->Upper(); ++aRefIndex)
1610       if (aPrevFeatureLabel == aRefs->Value(aRefIndex)) {
1611         if (aRefIndex == aRefs->Lower())
1612           aPrevFeatureLabel.Nullify();
1613         else
1614           aPrevFeatureLabel = aRefs->Value(aRefIndex - 1);
1615         break;
1616       }
1617
1618     // move the folder in the list of references before the first feature
1619     RemoveFromRefArray(aFeaturesLab, aFolderLabel);
1620     AddToRefArray(aFeaturesLab, aFolderLabel, aPrevFeatureLabel);
1621     // update first feature of the folder
1622     initFirstAttr = true;
1623   } else {
1624     // update last feature of the folder
1625     initLastAttr = true;
1626   }
1627
1628   if (initFirstAttr)
1629     aFirstFeatAttr->setValue(theFeatures.front());
1630   if (initLastAttr)
1631     aLastFeatAttr->setValue(theFeatures.back());
1632
1633   updateHistory(ModelAPI_Feature::group());
1634   return true;
1635 }
1636
1637 static FolderPtr isExtractionCorrect(const FolderPtr& theFirstFeatureFolder,
1638                                      const FolderPtr& theLastFeatureFolder,
1639                                      bool& isExtractBefore)
1640 {
1641   if (theFirstFeatureFolder.get()) {
1642     if (theLastFeatureFolder.get())
1643       return theFirstFeatureFolder == theLastFeatureFolder ? theFirstFeatureFolder : FolderPtr();
1644     else
1645       isExtractBefore = true;
1646     return theFirstFeatureFolder;
1647   } else if (theLastFeatureFolder.get()) {
1648     isExtractBefore = false;
1649     return theLastFeatureFolder;
1650   }
1651   // no folder found
1652   return FolderPtr();
1653 }
1654
1655 bool Model_Objects::removeFromFolder(
1656       const std::list<std::shared_ptr<ModelAPI_Feature> >& theFeatures,
1657       const bool theBefore)
1658 {
1659   if (theFeatures.empty())
1660     return false;
1661
1662   FolderPtr aFirstFeatureFolder =
1663       inFolder(theFeatures.front(), ModelAPI_Folder::FIRST_FEATURE_ID());
1664   FolderPtr aLastFeatureFolder =
1665       inFolder(theFeatures.back(),  ModelAPI_Folder::LAST_FEATURE_ID());
1666
1667   bool isExtractBeforeFolder = theBefore;
1668   FolderPtr aFoundFolder =
1669       isExtractionCorrect(aFirstFeatureFolder, aLastFeatureFolder, isExtractBeforeFolder);
1670   if (!aFoundFolder)
1671     return false; // list of features cannot be extracted
1672
1673   // references of the current folder
1674   ObjectPtr aFolderStartFeature;
1675   ObjectPtr aFolderEndFeature;
1676   if (aFirstFeatureFolder != aLastFeatureFolder) {
1677     aFolderStartFeature = aFoundFolder->reference(ModelAPI_Folder::FIRST_FEATURE_ID())->value();
1678     aFolderEndFeature   = aFoundFolder->reference(ModelAPI_Folder::LAST_FEATURE_ID())->value();
1679   }
1680
1681   FeaturePtr aFeatureToFind = isExtractBeforeFolder ? theFeatures.back() : theFeatures.front();
1682   std::shared_ptr<Model_Data> aData =
1683       std::static_pointer_cast<Model_Data>(aFeatureToFind->data());
1684   if (!aData || !aData->isValid())
1685     return false;
1686   TDF_Label aLabelToFind = aData->label().Father();
1687
1688   // search the label in the list of references
1689   TDF_Label aFeaturesLab = featuresLabel();
1690   Handle(TDataStd_ReferenceArray) aRefs;
1691   if (!aFeaturesLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
1692     return false; // no reference array (something is wrong)
1693   int aRefIndex = aRefs->Lower();
1694   for (; aRefIndex <= aRefs->Upper(); ++aRefIndex)
1695     if (aRefs->Value(aRefIndex) == aLabelToFind)
1696       break;
1697
1698   // update folder position
1699   if (isExtractBeforeFolder) {
1700     aData = std::dynamic_pointer_cast<Model_Data>(aFoundFolder->data());
1701     TDF_Label aFolderLabel = aData->label().Father();
1702     TDF_Label aPrevFeatureLabel = aRefs->Value(aRefIndex);
1703     // update start reference of the folder
1704     if (aFolderStartFeature.get()) {
1705       FeaturePtr aNewStartFeature;
1706       do { // skip all features placed in the composite features
1707         aPrevFeatureLabel = aRefs->Value(aRefIndex++);
1708         aNewStartFeature =
1709             aRefIndex <= aRefs->Upper() ? feature(aRefs->Value(aRefIndex)) : FeaturePtr();
1710       } while (aNewStartFeature && isSkippedFeature(aNewStartFeature));
1711       aFolderStartFeature = aNewStartFeature;
1712     }
1713     // move the folder in the list of references after the last feature from the list
1714     RemoveFromRefArray(aFeaturesLab, aFolderLabel);
1715     AddToRefArray(aFeaturesLab, aFolderLabel, aPrevFeatureLabel);
1716   } else {
1717     // update end reference of the folder
1718     if (aFolderEndFeature.get()) {
1719       FeaturePtr aNewEndFeature;
1720       do { // skip all features placed in the composite features
1721         --aRefIndex;
1722         aNewEndFeature =
1723             aRefIndex >= aRefs->Lower() ? feature(aRefs->Value(aRefIndex)) : FeaturePtr();
1724       } while (aNewEndFeature && isSkippedFeature(aNewEndFeature));
1725       aFolderEndFeature = aNewEndFeature;
1726     }
1727   }
1728
1729   // update folder references
1730   aFoundFolder->reference(ModelAPI_Folder::FIRST_FEATURE_ID())->setValue(aFolderStartFeature);
1731   aFoundFolder->reference(ModelAPI_Folder::LAST_FEATURE_ID())->setValue(aFolderEndFeature);
1732
1733   updateHistory(ModelAPI_Feature::group());
1734   return true;
1735 }
1736
1737 FolderPtr Model_Objects::findContainingFolder(const FeaturePtr& theFeature, int& theIndexInFolder)
1738 {
1739   // search the label in the list of references
1740   TDF_Label aFeaturesLab = featuresLabel();
1741   Handle(TDataStd_ReferenceArray) aRefs;
1742   if (!aFeaturesLab.FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs))
1743     return FolderPtr(); // no reference array (something is wrong)
1744
1745   std::shared_ptr<Model_Data> aData =
1746       std::static_pointer_cast<Model_Data>(theFeature->data());
1747   if (!aData || !aData->isValid())
1748     return FolderPtr();
1749   TDF_Label aLabelToFind = aData->label().Father();
1750
1751   theIndexInFolder = -1;
1752   FolderPtr aFoundFolder;
1753   TDF_Label aLastFeatureLabel;
1754
1755   for (int aRefIndex = aRefs->Lower(); aRefIndex <= aRefs->Upper(); ++aRefIndex) {
1756     TDF_Label aCurLabel = aRefs->Value(aRefIndex);
1757
1758     if (aFoundFolder)
1759       ++theIndexInFolder;
1760
1761     if (aCurLabel == aLabelToFind) { // the feature is reached
1762       if (aFoundFolder) {
1763         if (isSkippedFeature(theFeature)) {
1764           theIndexInFolder = -1;
1765           return FolderPtr();
1766         }
1767         // decrease the index of the feature in the folder by the number of skipped features
1768         for (int anIndex = theIndexInFolder - 1; anIndex > 0; anIndex--) {
1769           aCurLabel = aRefs->Value(aRefIndex - anIndex);
1770           if (isSkippedFeature(feature(aCurLabel)))
1771             theIndexInFolder--;
1772         }
1773       }
1774       return aFoundFolder;
1775     }
1776
1777     if (!aFoundFolder) {
1778       // if the current label refers to a folder, feel all necessary data
1779       const ObjectPtr& aFolderObj = folder(aCurLabel);
1780       if (aFolderObj.get()) {
1781         aFoundFolder = std::dynamic_pointer_cast<ModelAPI_Folder>(aFolderObj);
1782         theIndexInFolder = -1;
1783
1784         AttributeReferencePtr aLastRef =
1785             aFoundFolder->reference(ModelAPI_Folder::LAST_FEATURE_ID());
1786         if (aLastRef->value()) {
1787           aData = std::static_pointer_cast<Model_Data>(aLastRef->value()->data());
1788           if (aData && aData->isValid())
1789             aLastFeatureLabel = aData->label().Father();
1790         } else // folder is empty
1791           aFoundFolder = FolderPtr();
1792       }
1793     } else if (aLastFeatureLabel == aCurLabel) {
1794       // folder is finished, clear all stored data
1795       theIndexInFolder = -1;
1796       aFoundFolder = FolderPtr();
1797     }
1798   }
1799
1800   // folder is not found
1801   theIndexInFolder = -1;
1802   return FolderPtr();
1803 }
1804
1805
1806 std::shared_ptr<ModelAPI_Feature> Model_Objects::feature(
1807     const std::shared_ptr<ModelAPI_Result>& theResult)
1808 {
1809   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(theResult->data());
1810   if (aData.get() && aData->isValid()) {
1811     TDF_Label aFeatureLab = aData->label().Father().Father().Father();
1812     FeaturePtr aFeature = feature(aFeatureLab);
1813     while(!aFeature.get() && aFeatureLab.Depth() > 1) { // this may be sub-result of result
1814       aFeatureLab = aFeatureLab.Father().Father();
1815       aFeature = feature(aFeatureLab);
1816     }
1817     return aFeature;
1818   }
1819   return FeaturePtr();
1820 }
1821
1822 std::string Model_Objects::featureResultGroup(FeaturePtr theFeature)
1823 {
1824   if (theFeature->data()->isValid()) {
1825     TDF_ChildIterator aLabIter(resultLabel(theFeature->data(), 0).Father());
1826     if (aLabIter.More()) {
1827       TDF_Label anArgLab = aLabIter.Value();
1828       Handle(TDataStd_Comment) aGroup;
1829       if (aLabIter.Value().FindAttribute(TDataStd_Comment::GetID(), aGroup)) {
1830         return TCollection_AsciiString(aGroup->Get()).ToCString();
1831       }
1832     }
1833   }
1834   static std::string anEmpty;
1835   return anEmpty; // not found
1836 }
1837
1838 void Model_Objects::updateResults(FeaturePtr theFeature, std::set<FeaturePtr>& theProcessed)
1839 {
1840   if (theProcessed.find(theFeature) != theProcessed.end())
1841     return;
1842   theProcessed.insert(theFeature);
1843   // for composites update subs recursively (sketch elements results are needed for the sketch)
1844   CompositeFeaturePtr aComp = std::dynamic_pointer_cast<ModelAPI_CompositeFeature>(theFeature);
1845   if (aComp.get() && aComp->getKind() != "Part") { // don't go inside of parts sub-features
1846     // update subs of composites first
1847     int aSubNum = aComp->numberOfSubs();
1848     for(int a = 0; a < aSubNum; a++) {
1849       FeaturePtr aSub = aComp->subFeature(a);
1850       updateResults(aComp->subFeature(a), theProcessed);
1851     }
1852   }
1853
1854   // it may be on undo
1855   if (!theFeature->data() || !theFeature->data()->isValid() || theFeature->isDisabled())
1856     return;
1857
1858   // check the existing results and remove them if there is nothing on the label
1859   std::list<ResultPtr>::const_iterator aResIter = theFeature->results().cbegin();
1860   while(aResIter != theFeature->results().cend()) {
1861     ResultPtr aBody = std::dynamic_pointer_cast<ModelAPI_Result>(*aResIter);
1862     if (aBody.get()) {
1863       std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(aBody->data());
1864       if (!aData.get() || !aData->isValid() || (!aBody->isDisabled() && aData->isDeleted())) {
1865         // found a disappeared result => remove it
1866         theFeature->eraseResultFromList(aBody);
1867         // start iterate from beginning because iterator is corrupted by removing
1868         aResIter = theFeature->results().cbegin();
1869         continue;
1870       }
1871     }
1872     aResIter++;
1873   }
1874   // check that results are presented on all labels
1875   int aResSize = int(theFeature->results().size());
1876   TDF_ChildIterator aLabIter(resultLabel(theFeature->data(), 0).Father());
1877   for(; aLabIter.More(); aLabIter.Next()) {
1878     // here must be GUID of the feature
1879     int aResIndex = aLabIter.Value().Tag() - 1;
1880     ResultPtr aNewBody;
1881     if (aResSize <= aResIndex) {
1882       TDF_Label anArgLab = aLabIter.Value();
1883       Handle(TDataStd_Comment) aGroup;
1884       if (anArgLab.FindAttribute(TDataStd_Comment::GetID(), aGroup)) {
1885         if (aGroup->Get() == ModelAPI_ResultBody::group().c_str()) {
1886           aNewBody = createBody(theFeature->data(), aResIndex);
1887         } else if (aGroup->Get() == ModelAPI_ResultPart::group().c_str()) {
1888           if (aResIndex <= theFeature->results().size()) { // to avoid crash if previous execute
1889             // for index = 0 erases result
1890             std::shared_ptr<ModelAPI_ResultPart> aNewP = createPart(theFeature->data(), aResIndex);
1891             if (!aNewP->data()->isDeleted()) {
1892               theFeature->setResult(aNewP, aResIndex);
1893               if (!aNewP->partDoc().get())
1894                 // create the part result: it is better to restore the previous result if possible
1895                 theFeature->execute();
1896             }
1897           }
1898         } else if (aGroup->Get() == ModelAPI_ResultConstruction::group().c_str()) {
1899           ResultConstructionPtr aConstr = createConstruction(theFeature->data(), aResIndex);
1900           if (!aConstr->updateShape())
1901             theFeature->execute(); // not stored shape in the data structure, execute to have it
1902           else
1903             theFeature->setResult(aConstr, aResIndex); // result is ready without execution
1904         } else if (aGroup->Get() == ModelAPI_ResultGroup::group().c_str()) {
1905           aNewBody = createGroup(theFeature->data(), aResIndex);
1906         } else if (aGroup->Get() == ModelAPI_ResultField::group().c_str()) {
1907           ResultFieldPtr aField = createField(theFeature->data(), aResIndex);
1908           aField->updateSteps(); // to refresh the internal data
1909           aNewBody = aField;
1910         } else if (aGroup->Get() == ModelAPI_ResultParameter::group().c_str()) {
1911           theFeature->attributeChanged("expression"); // just produce a value
1912         } else {
1913           Events_InfoMessage("Model_Objects", "Unknown type of result is found in the document:")
1914             .arg(TCollection_AsciiString(aGroup->Get()).ToCString()).send();
1915         }
1916       }
1917       if (aNewBody && !aNewBody->data()->isDeleted()) {
1918         theFeature->setResult(aNewBody, aResIndex);
1919       }
1920     }
1921   }
1922   if (aResSize > 0) { // check there exist a body that must be updated
1923     std::list<ResultPtr>::const_iterator aRes = theFeature->results().cbegin();
1924     for (; aResSize && aRes != theFeature->results().cend(); aRes++, aResSize++) {
1925       if ((*aRes)->data()->isValid()) {
1926         if ((*aRes)->groupName() == ModelAPI_ResultBody::group()) {
1927           ResultBodyPtr aBody = std::dynamic_pointer_cast<ModelAPI_ResultBody>(*aRes);
1928           aBody->updateSubs(aBody->shape(), false);
1929         } else if ((*aRes)->groupName() == ModelAPI_ResultConstruction::group()) {
1930           // update the cashed myShape presented in construction
1931           ResultConstructionPtr aConstr =
1932             std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(*aRes);
1933           aConstr->updateShape();
1934         }
1935       }
1936     }
1937   }
1938 }
1939
1940 ResultPtr Model_Objects::findByName(const std::wstring theName)
1941 {
1942   ResultPtr aResult;
1943   FeaturePtr aResFeature; // keep feature to return the latest one
1944   NCollection_DataMap<TDF_Label, FeaturePtr>::Iterator anObjIter(myFeatures);
1945   for(; anObjIter.More(); anObjIter.Next()) {
1946     FeaturePtr& aFeature = anObjIter.ChangeValue();
1947     if (!aFeature.get() || aFeature->isDisabled()) // may be on close
1948       continue;
1949     std::list<ResultPtr> allResults;
1950     ModelAPI_Tools::allResults(aFeature, allResults);
1951     std::list<ResultPtr>::iterator aRIter = allResults.begin();
1952     for (; aRIter != allResults.cend(); aRIter++) {
1953       ResultPtr aRes = *aRIter;
1954       if (aRes.get() && aRes->data() && aRes->data()->isValid() && !aRes->isDisabled() &&
1955           aRes->data()->name() == theName)
1956       {
1957         if (!aResult.get() || isLater(aFeature, aResFeature)) { // select the latest
1958           aResult = aRes;
1959           aResFeature = aFeature;
1960         }
1961       }
1962     }
1963   }
1964   return aResult;
1965 }
1966
1967 TDF_Label Model_Objects::nextLabel(TDF_Label theCurrent, int& theIndex, const bool theReverse)
1968 {
1969   Handle(TDataStd_ReferenceArray) aRefs;
1970   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
1971     int aStart = theIndex == kUNDEFINED_FEATURE_INDEX ? aRefs->Lower() : theIndex;
1972     for(int a = aStart; a <= aRefs->Upper(); a++) { // iterate all existing features
1973       TDF_Label aCurLab = aRefs->Value(a);
1974       if (aCurLab.IsEqual(theCurrent)) {
1975         a += theReverse ? -1 : 1;
1976         if (a >= aRefs->Lower() && a <= aRefs->Upper()) {
1977           theIndex = a;
1978           return aRefs->Value(a);
1979         }
1980         break; // finish iteration: it's last feature
1981       }
1982     }
1983   }
1984   return TDF_Label();
1985 }
1986
1987 FeaturePtr Model_Objects::nextFeature(FeaturePtr theCurrent, int& theIndex, const bool theReverse)
1988 {
1989   std::shared_ptr<Model_Data> aData = std::static_pointer_cast<Model_Data>(theCurrent->data());
1990   if (aData.get() && aData->isValid()) {
1991     TDF_Label aFeatureLabel = aData->label().Father();
1992     do {
1993       TDF_Label aNextLabel = nextLabel(aFeatureLabel, theIndex, theReverse);
1994       if (aNextLabel.IsNull())
1995         break; // the last or something is wrong
1996       FeaturePtr aFound = feature(aNextLabel);
1997       if (aFound)
1998         return aFound; // the feature is found
1999       // if the next label is a folder, skip it
2000       aFeatureLabel = folder(aNextLabel).get() ? aNextLabel : TDF_Label();
2001     } while (!aFeatureLabel.IsNull());
2002   }
2003   return FeaturePtr(); // not found, last, or something is wrong
2004 }
2005
2006 FeaturePtr Model_Objects::firstFeature()
2007 {
2008   Handle(TDataStd_ReferenceArray) aRefs;
2009   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
2010     return feature(aRefs->Value(aRefs->Lower()));
2011   }
2012   return FeaturePtr(); // no features at all
2013 }
2014
2015 FeaturePtr Model_Objects::lastFeature()
2016 {
2017   Handle(TDataStd_ReferenceArray) aRefs;
2018   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
2019     // comment this because of #2674 - features are removed from array on deactivation of Part
2020     /*FeaturePtr aLast = feature(aRefs->Value(aRefs->Upper()));
2021     if (!aLast.get() && aRefs->Length() != 0) { // erase the invalid feature from the array
2022       RemoveFromRefArray(featuresLabel(), aRefs->Value(aRefs->Upper()));
2023       return lastFeature(); // try once again, after the last was removed
2024     }*/
2025     return feature(aRefs->Value(aRefs->Upper()));
2026   }
2027   return FeaturePtr(); // no features at all
2028 }
2029
2030 bool Model_Objects::isLater(FeaturePtr theLater, FeaturePtr theCurrent) const
2031 {
2032   std::shared_ptr<Model_Data> aLaterD = std::static_pointer_cast<Model_Data>(theLater->data());
2033   std::shared_ptr<Model_Data> aCurrentD = std::static_pointer_cast<Model_Data>(theCurrent->data());
2034   if (aLaterD.get() && aLaterD->isValid() && aCurrentD.get() && aCurrentD->isValid()) {
2035     TDF_Label aLaterL = aLaterD->label().Father();
2036     TDF_Label aCurrentL = aCurrentD->label().Father();
2037     int aLaterI = -1, aCurentI = -1; // not found yet state
2038     Handle(TDataStd_ReferenceArray) aRefs;
2039     if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
2040       for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) { // iterate all existing features
2041         TDF_Label aCurLab = aRefs->Value(a);
2042         if (aCurLab.IsEqual(aLaterL)) {
2043           aLaterI = a;
2044         } else if (aCurLab.IsEqual(aCurrentL)) {
2045           aCurentI = a;
2046         } else continue;
2047         if (aLaterI != -1 && aCurentI != -1) // both are found
2048           return aLaterI > aCurentI;
2049       }
2050     }
2051   }
2052   return false; // not found, or something is wrong
2053 }
2054
2055 std::list<std::shared_ptr<ModelAPI_Object> > Model_Objects::allObjects()
2056 {
2057   std::list<std::shared_ptr<ModelAPI_Object> > aResult;
2058   Handle(TDataStd_ReferenceArray) aRefs;
2059   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
2060     for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
2061       ObjectPtr anObject = object(aRefs->Value(a));
2062       if (!anObject.get()) // is it a folder?
2063         anObject = folder(aRefs->Value(a));
2064       if (anObject.get())
2065         aResult.push_back(anObject);
2066     }
2067   }
2068   return aResult;
2069 }
2070
2071 std::list<std::shared_ptr<ModelAPI_Feature> > Model_Objects::allFeatures()
2072 {
2073   std::list<std::shared_ptr<ModelAPI_Feature> > aResult;
2074   Handle(TDataStd_ReferenceArray) aRefs;
2075   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
2076     for(int a = aRefs->Lower(); a <= aRefs->Upper(); a++) {
2077       FeaturePtr aFeature = feature(aRefs->Value(a));
2078       if (aFeature.get())
2079         aResult.push_back(aFeature);
2080     }
2081   }
2082   return aResult;
2083 }
2084
2085 int Model_Objects::numInternalFeatures()
2086 {
2087   Handle(TDataStd_ReferenceArray) aRefs;
2088   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
2089     return aRefs->Upper() - aRefs->Lower() + 1;
2090   }
2091   return 0; // invalid
2092 }
2093
2094 std::shared_ptr<ModelAPI_Feature> Model_Objects::internalFeature(const int theIndex)
2095 {
2096   Handle(TDataStd_ReferenceArray) aRefs;
2097   if (featuresLabel().FindAttribute(TDataStd_ReferenceArray::GetID(), aRefs)) {
2098     return feature(aRefs->Value(aRefs->Lower() + theIndex));
2099   }
2100   return FeaturePtr(); // invalid
2101 }
2102
2103 Standard_Integer HashCode(const TDF_Label& theLab, const Standard_Integer theUpper)
2104 {
2105   return TDF_LabelMapHasher::HashCode(theLab, theUpper);
2106
2107 }
2108 Standard_Boolean IsEqual(const TDF_Label& theLab1, const TDF_Label& theLab2)
2109 {
2110   return TDF_LabelMapHasher::IsEqual(theLab1, theLab2);
2111 }