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