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